JavaScript Objects
5 April 2025 | Category: JavaScript
đ What is an Object in JavaScript?
In JavaScript, an object is a collection of key-value pairs.
Think of it like a real-world item â for example, a car has properties like color, model, and speed.
In code, we store such related data in objects.
đ ď¸ 1. Creating an Object
const person = {
name: "Alice",
age: 25,
isStudent: false
};
name
,age
, andisStudent
are keys (or properties)"Alice"
,25
, andfalse
are values
đ 2. Accessing Object Properties
⤠Dot Notation:
console.log(person.name); // Alice
⤠Bracket Notation:
console.log(person["age"]); // 25
Use bracket notation if the key has spaces or is stored in a variable.
âď¸ 3. Modifying Object Properties
person.age = 26; // Change value
person["isStudent"] = true; // Change using brackets
â 4. Adding New Properties
person.city = "Delhi";
â 5. Deleting Properties
delete person.isStudent;
đ 6. Looping Through Object Properties
for (let key in person) {
console.log(key + ":", person[key]);
}
đ§ 7. Nested Objects
const user = {
name: "John",
address: {
city: "Mumbai",
zip: 400001
}
};
console.log(user.address.city); // Mumbai
đŚ 8. Object Methods (Function inside an Object)
const user = {
name: "Ravi",
greet: function() {
console.log("Hello, " + this.name);
}
};
user.greet(); // Hello, Ravi
this
refers to the object itself.
đ 9. Object.keys(), Object.values(), Object.entries()
const product = { name: "Phone", price: 500 };
console.log(Object.keys(product)); // ["name", "price"]
console.log(Object.values(product)); // ["Phone", 500]
console.log(Object.entries(product));// [["name", "Phone"], ["price", 500]]
đ§Ź 10. Spread Operator with Objects
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const combined = { ...obj1, ...obj2 };
console.log(combined); // { a: 1, b: 2 }
đ 11. Object Destructuring
const car = {
brand: "BMW",
color: "Black"
};
const { brand, color } = car;
console.log(brand); // BMW
console.log(color); // Black
đ Summary
Operation | Example |
---|---|
Create object | const obj = { key: value } |
Access property | obj.key or obj["key"] |
Modify property | obj.key = newValue |
Add property | obj.newKey = value |
Delete property | delete obj.key |
Loop through object | for (let key in obj) |
Get keys/values | Object.keys(obj) |
Destructure object | const { a, b } = obj |