Objects are variables too, but they can contain multiple values. In real life, a car is an object. A car has properties like weight and color, and methods like start and stop.
You define (and create) a JavaScript object with an object literal using curly braces
{}.
const person = {
firstName: "Mim",
lastName: "Akter",
age: 25,
eyeColor: "brown"
};
The name:value pairs in JavaScript objects are called properties.
| Property | Property Value |
|---|---|
| firstName | "Mim" |
| lastName | "Akter" |
| age | 25 |
You can access object properties in two ways:
This is the most common and readable way.
console.log(person.firstName); // "Mim"
This is useful if the property name is stored in a variable or contains spaces.
console.log(person["firstName"]); // "Mim"
Objects can also have methods. Methods are actions that can be performed on objects. A method is simply a property containing a function definition.
const person = {
firstName: "Mim",
lastName: "Akter",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // "Mim Akter"
this refers to the
"owner" of the function. In the example above, this is the
person object.
name:value pairsthis keyword refers to the current objectconst when declaring objects as standard practice