In JavaScript, an object is a collection of key-value pairs (also called properties).
Objects help store and organize related data and functions in one place.
const person = {
firstName: "Alice",
lastName: "Johnson",
age: 30,
isStudent: false
};firstName, lastName, age, isStudent are keys (properties)"Alice", "Johnson", 30, false are valuesconsole.log(person.firstName); // Output: Aliceconsole.log(person["lastName"]); // Output: JohnsonUse brackets when:
person.age = 31;person.country = "India";delete person.isStudent;A method is a function inside an object.
const car = {
brand: "Toyota",
model: "Camry",
start: function () {
console.log("Engine started");
}
};
car.start(); // Output: Engine startedYou can also use shorthand syntax:
const car = {
brand: "Toyota",
start() {
console.log("Engine started");
}
};Inside an object method, this refers to the object itself.
const user = {
name: "Sara",
greet() {
console.log("Hi, I'm " + this.name);
}
};
user.greet(); // Output: Hi, I'm SaraObjects can contain other objects.
const student = {
name: "John",
grades: {
math: 90,
english: 85
}
};
console.log(student.grades.math); // Output: 90const book = {
title: "1984",
author: "George Orwell"
};
for (let key in book) {
console.log(key + ": " + book[key]);
}Returns an array of keys.
Object.keys(book); // ['title', 'author']Returns an array of values.
Object.values(book); // ['1984', 'George Orwell']Returns an array of [key, value] pairs.
Object.entries(book);
// [['title', '1984'], ['author', 'George Orwell']]Extract values into variables easily.
const user = {
name: "Liam",
age: 25
};
const { name, age } = user;
console.log(name); // Liam
console.log(age); // 25Useful for storing lists of items (e.g., users, products).
const users = [
{ name: "Alice", age: 20 },
{ name: "Bob", age: 25 }
];
console.log(users[1].name); // Output: Bob| Feature | Example |
|---|---|
| Create object | const obj = { key: value } |
| Access property | obj.key or obj["key"] |
| Add/update property | obj.newKey = value |
| Delete property | delete obj.key |
| Object method | obj.method = function() {} |
Use this | Inside method: refers to object |
| Loop object | for (let key in obj) |
| Destructuring | const { key } = obj |
movie with keys: title, director, year.getDetails that returns a formatted string using this.title, etc.movie object.