Objects are one of the most important data structures in JavaScript. They allow you to store data as key-value pairs, making it easy to organize and manipulate complex information.
This blog will explain objects, their properties, methods, and practical examples.
⭐ 1. What Is an Object?
An object is a collection of properties.
Each property is a key (name) and a value.
Example:
let user = {
name: "Sagar",
age: 22,
city: "Ludhiana"
};
console.log(user.name); // Sagar
console.log(user["city"]); // Ludhiana
⭐ 2. Creating Objects
Using Object Literal
let car = {
brand: "Honda",
model: "City",
year: 2023
};
Using Object Constructor
let car = new Object();
car.brand = "Honda";
car.model = "City";
car.year = 2023;
⭐ 3. Accessing Object Properties
You can access properties in two ways:
Dot Notation
console.log(car.brand); // Honda
Bracket Notation
console.log(car["model"]); // City
⭐ 4. Modifying Object Properties
You can update or add new properties anytime.
car.year = 2024; // Update
car.color = "Red"; // Add new property
console.log(car);
⭐ 5. Object Methods
Objects can have functions as properties, called methods.
let user = {
name: "Sagar",
greet: function() {
console.log("Hello, " + this.name);
}
};
user.greet(); // Hello, Sagar
ES6 Method Shorthand
let user = {
name: "Sagar",
greet() {
console.log("Hello, " + this.name);
}
};
user.greet(); // Hello, Sagar
⭐ 6. Looping Through Objects
for…in Loop
for (let key in user) {
console.log(key + ": " + user[key]);
}
⭐ 7. Object Destructuring (ES6)
Easily extract properties into variables.
let {name, age} = user;
console.log(name); // Sagar
console.log(age); // 22
⭐ 8. Object Methods: Object.keys(), Object.values(), Object.entries()
console.log(Object.keys(user)); // ["name","greet"]
console.log(Object.values(user)); // ["Sagar", function]
console.log(Object.entries(user)); // [["name","Sagar"], ["greet",function]]
⭐ Conclusion
Objects are a fundamental part of JavaScript. They allow you to store complex data, define methods, and structure your code efficiently. Mastering objects is essential for building dynamic web applications.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/