Object in JavaScript
🧠 What is an Object?
In JavaScript, an object is a complex data type used to store collections of key-value pairs. Objects let you group related data and behavior (via methods) together.
>>“Objects are the building blocks of structured JavaScript applications.” 🏗️
📌 Creating an Object
You can create an object using curly braces with keys and values:
Basic Object
const person = {
name: "Alice",
age: 30,
isDeveloper: true
};Note
💡 Keys (also called properties) are always strings or symbols. Values can be any data type.
🛠 Accessing Object Properties
You can access properties using dot notation or bracket notation:
Property Access
console.log(person.name); // Alice
console.log(person["age"]); // 30
// Dynamic key access
let key = "isDeveloper";
console.log(person[key]); // true🔄 Modifying Objects
Update, Add, and Delete Properties
person.age = 31; // Update
person.city = "New York"; // Add new
delete person.isDeveloper; // Delete property🔁 Looping Through an Object
Use for...in to iterate over properties:
Looping Over Object Keys
for (let key in person) {
console.log(key, person[key]);
}Note
🧠 To iterate over only keys or values, use Object.keys(), Object.values(), or Object.entries().
🧬 Nested Objects
Objects can contain other objects, creating a deep structure:
Nested Object
const user = {
name: "Bob",
contact: {
email: "bob@example.com",
phone: "123-456"
}
};
console.log(user.contact.email);🧪 Methods in Objects
Objects can also contain functions called methods:
Object with Methods
const car = {
brand: "Tesla",
drive: function() {
console.log("Vroom!");
}
};
car.drive(); // Vroom!Note
🔥 ES6 shorthand lets you write drive() { ... } instead of drive: function() { ... }.
🚀 Object Utilities
| Method | Description |
|---|---|
| Object.keys(obj) | Returns array of property keys |
| Object.values(obj) | Returns array of property values |
| Object.entries(obj) | Returns array of [key, value] pairs |
| Object.assign(target, source) | Copies properties to target |
| Object.hasOwn(obj, key) | Checks if key exists on object |
| Object.freeze(obj) | Makes object immutable |
⚠️ Objects vs Arrays
Both objects and arrays are used for grouping values. But:
- 📦 Use objects for named values (key-value pairs)
- 📚 Use arrays for ordered collections (lists)
📖 Resources
🔚 Summary
- Objects store data using key: value pairs
- Use dot or bracket notation to access properties
- Can contain nested data and functions (methods)
- Objects are essential for real-world apps and data modeling
>>“Objects give your data a meaningful structure — use them to build real-world logic.” 🧠