In JavaScript, an object is a collection of related data stored as key–value pairs. Objects help organize data logically and are widely used in real-world applications.
Objects are useful when you need to store multiple related values together.
let name = "John";
let age = 25;
let city = "Delhi";
let user = {
name: "John",
age: 25,
city: "Delhi"
};
let person = {
name: "Emma",
age: 30,
isStudent: false
};
console.log(person.name); // Emma
console.log(person["age"]); // 30
Use bracket notation when the property name is dynamic or contains spaces.
person.age = 31;
person.name = "Emma Watson";
person.country = "India";
person.email = "emma@example.com";
delete person.isStudent;
Objects can contain functions, called methods.
let car = {
brand: "Tesla",
model: "Model S",
start: function () {
console.log("Car started");
}
};
car.start();
Objects can contain other objects.
let student = {
name: "Amit",
marks: {
math: 90,
science: 85
}
};
console.log(student.marks.math); // 90
Used frequently in real applications like user lists or product lists.
let users = [
{ name: "John", age: 25 },
{ name: "Emma", age: 30 },
{ name: "Alex", age: 22 }
];
console.log(users[1].name); // Emma
let user = {
name: "John",
age: 25,
city: "Delhi"
};
for (let key in user) {
console.log(key + ": " + user[key]);
}
Object.keys()
Object.keys(user);
// ["name", "age", "city"]
Object.values(user);
// ["John", 25, "Delhi"]
Object.entries(user);
// [["name","John"],["age",25],["city","Delhi"]]
| Feature | Description | Example |
|---|---|---|
| Create Object | Group related data | { name: "John" } |
| Access Value | Get property value | obj.name |
| Update Value | Change property | obj.age = 30 |
| Add Property | Add new key | obj.city = "Delhi" |
| Delete Property | Remove key | delete obj.city |
| Loop Object | Iterate keys | for (key in obj) |