An object is a non-primitive data type in JavaScript that allows you to store multiple collections of data. Unlike arrays that use indexes, objects use key-value pairs. Keys are strings (or Symbols), and values can be any data type, including other objects or functions.
The most common way to create an object is using the Object Literal syntax {}.
const person = {
firstName: "Ragini",
lastName: "Singh",
age: 24,
isStudent: false
};
document.write(person);
You can access object properties in two ways:
obj.key (Most common)obj["key"] (Useful for dynamic keys or keys with spaces)
const car = { brand: "Toyota", model: "Corolla", "fuel type": "Hybrid" };
document.write(car.brand); // Dot notation
document.write(car["model"]); // Bracket notation
document.write(car["fuel type"]); // Bracket notation required for spaces
Objects are mutable. You can add, update, or delete properties even if declared with
const.
const user = { name: "Alex", role: "User" };
// Add property
user.email = "alex@example.com";
// Update property
user.role = "Admin";
// Delete property
delete user.name;
document.write(user);
A method is a function stored as a property. The this keyword refers to the object itself.
const student = {
name: "Ravi",
greet: function() {
return "Hello, I am " + this.name;
}
};
document.write(student.greet());
Use the for...in loop to iterate through keys.
const book = { title: "JS Guide", author: "John", pages: 300 };
for (let key in book) {
document.write(key + ": " + book[key]);
}
JavaScript provides static methods to work with objects.
const data = { a: 1, b: 2, c: 3 };
document.write(Object.keys(data)); // ["a", "b", "c"]
document.write(Object.values(data)); // [1, 2, 3]
document.write(Object.entries(data));// [["a", 1], ["b", 2], ["c", 3]]
Objects can contain other objects.
const employee = {
id: 101,
details: {
city: "Mumbai",
pincode: 400001
}
};
document.write(employee.details.city); // Mumbai
| Feature | Array [] | Object {} |
|---|---|---|
| Structure | Ordered List | Key-Value Pairs |
| Access | Index (0, 1, 2) | Key ("name", "age") |
| Best For | Lists of similar items | Describing a single entity |
user.email). Use arrays
when you have a list of items (e.g., users[0]).
Test your understanding of JavaScript Objects.
car.brand set to "Toyota".model set to "Corolla".const user = { name: "Alice", email: "alice@example.com" };email property.const book = { title: "1984", author: "George Orwell" };year with the value 2022.year property to the console.const student = { name: "John", grade: "A", age: 18 };for...in loop to iterate through all the keys.person with properties firstName: "John" and lastName: "Doe".getFullName inside the object.firstName and lastName using the this keyword.