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=== and expecting content equality. {a: 1} === {a: 1} is always false — objects compare by reference, not by their properties, even when the contents look identical.
setTimeout(person.fullName) loses track of this, since the function is called without its object context. Use an arrow function wrapper or .bind() instead.
let b = a; makes b point to the same object as a — changing one changes both. Use {...a} for a shallow copy.
A second example — an object with both data and a method that uses that data:
const cartItem = {
name: "Wireless Mouse",
price: 25,
quantity: 2,
subtotal: function() {
return this.price * this.quantity;
}
};
console.log(cartItem.subtotal()); // 50
Q: Why are two objects with the same properties not equal with ===?
A: Because === checks whether both variables point to the exact same object in memory, not whether their contents match. Compare specific properties, or use a deep-equality helper if you need content comparison.
Q: How do I copy an object without both variables pointing to the same one?
A: Use the spread operator: let copy = {...original};. Note this is a shallow copy — nested objects inside are still shared.
Q: What is object destructuring?
A: A shorthand for pulling properties into variables: const { name, price } = cartItem;. See the MDN destructuring guide for the full syntax.