In JavaScript, objects are used to store key-value pairs, allowing you to group related data and functions. They are essential for representing complex entities like users, products, or configurations.
1. Creating Objects
There are multiple ways to create objects:
// Using object literal
let person = {
name: "Alice",
age: 25,
isActive: true
};
// Using Object constructor
let car = new Object();
car.brand = "Toyota";
car.model = "Corolla";
console.log(person.name); // Output: Alice
2. Accessing and Modifying Properties
You can access properties using dot notation or bracket notation:
console.log(person.age); // 25
console.log(person["name"]); // Alice
// Modify property
person.age = 26;
person["isActive"] = false;
console.log(person.age); // 26
console.log(person.isActive); // false
3. Adding and Deleting Properties
// Adding new property
person.city = "New York";
console.log(person.city); // New York
// Deleting a property
delete person.isActive;
console.log(person.isActive); // undefined
4. Object Methods
Objects can contain functions called methods:
let calculator = {
add: function(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // 8
console.log(calculator.subtract(10, 4)); // 6
5. Iterating Over Objects
You can loop through object properties using for...in:
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// name: Alice
// age: 26
// city: New York
- For more advanced iteration,
Object.keys(),Object.values(), andObject.entries()can be used:
console.log(Object.keys(person)); // ["name", "age", "city"]
console.log(Object.values(person)); // ["Alice", 26, "New York"]
6. Practical Tips
- Objects are ideal for representing real-world entities with multiple properties.
- Use methods to encapsulate behavior related to an object.
- Avoid mutating objects directly when possible — use techniques like Object.assign or spread operator to create copies.
Mastering objects is essential for data organization, APIs, and complex application logic in JavaScript.
Citations: