JavaScript Objects
An object is a collection of related data and functionality grouped together. Objects represent real-world entities using key-value pairs, where each key is a property name and each value is the data associated with it.
Real-life analogy: Think of an object like a person's ID card — it has multiple details like name, age, address, and photo, all organized together as one unit.
Creating an Object
Objects are created using curly braces { }, with properties written as key: value pairs separated by commas.
let student = {
name: "Riya",
age: 21,
course: "Computer Science",
isEnrolled: true
};
console.log(student);Accessing Object Properties
There are two ways to access properties from an object:
Dot Notation (Most Common)
let car = {
brand: "Toyota",
model: "Fortuner",
year: 2023
};
console.log(car.brand); // Toyota
console.log(car.year); // 2023Bracket Notation (Used When Key is Dynamic or Has Special Characters)
console.log(car["model"]); // Fortuner
let key = "year";
console.log(car[key]); // 2023Modifying Object Properties
Properties of an object can be updated by assigning a new value to the property key.
let person = {
name: "Arjun",
age: 25
};
person.age = 26; // Update existing property
person.city = "Bengaluru"; // Add new property
console.log(person);
// { name: "Arjun", age: 26, city: "Bengaluru" }Deleting Object Properties
The delete keyword removes a property from an object.
let product = {
name: "Laptop",
price: 55000,
discount: 5000
};
delete product.discount;
console.log(product);
// { name: "Laptop", price: 55000 }Methods — Functions Inside Objects
When a function is stored as a property inside an object, it is called a method. Methods define the behavior of an object.
let calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
console.log(calculator.add(10, 5)); // 15
console.log(calculator.subtract(10, 5)); // 5Shorthand Method Syntax (ES6)
let calculator = {
add(a, b) {
return a + b;
},
multiply(a, b) {
return a * b;
}
};
console.log(calculator.multiply(4, 6)); // 24The this Keyword
Inside an object's method, this refers to the object itself. It is used to access other properties of the same object.
let employee = {
name: "Deepa",
salary: 50000,
greet() {
console.log("Hello, I am " + this.name);
},
annualSalary() {
return this.salary * 12;
}
};
employee.greet();
console.log(employee.annualSalary()); // 600000Checking if a Property Exists
The in operator checks whether a property exists in an object.
let user = {
username: "admin",
role: "manager"
};
console.log("username" in user); // true
console.log("email" in user); // falseLooping Through Object Properties
The for...in loop iterates over all properties of an object.
let laptop = {
brand: "Dell",
ram: "16GB",
storage: "512GB SSD",
price: 65000
};
for (let key in laptop) {
console.log(key + ": " + laptop[key]);
}
// Output:
// brand: Dell
// ram: 16GB
// storage: 512GB SSD
// price: 65000Object Methods — Built-in Helpers
Object.keys() — Get All Property Names
let person = { name: "Suresh", age: 30, city: "Hyderabad" };
let keys = Object.keys(person);
console.log(keys); // ["name", "age", "city"]Object.values() — Get All Property Values
let values = Object.values(person);
console.log(values); // ["Suresh", 30, "Hyderabad"]Object.entries() — Get Key-Value Pairs as Arrays
let entries = Object.entries(person);
console.log(entries);
// [["name", "Suresh"], ["age", 30], ["city", "Hyderabad"]]Object.assign() — Copy or Merge Objects
let defaults = { theme: "light", language: "English" };
let userSettings = { language: "Hindi", fontSize: 16 };
let finalSettings = Object.assign({}, defaults, userSettings);
console.log(finalSettings);
// { theme: "light", language: "Hindi", fontSize: 16 }Object Destructuring
Destructuring allows extracting properties from an object into separate variables cleanly.
let phone = {
brand: "Samsung",
model: "Galaxy S23",
price: 80000
};
let { brand, model, price } = phone;
console.log(brand); // Samsung
console.log(model); // Galaxy S23
console.log(price); // 80000Destructuring with a Different Variable Name
let { brand: phoneBrand, price: phonePrice } = phone;
console.log(phoneBrand); // Samsung
console.log(phonePrice); // 80000Spread Operator with Objects
The spread operator ... can copy or merge objects.
let original = { a: 1, b: 2 };
let copy = { ...original, c: 3 };
console.log(copy); // { a: 1, b: 2, c: 3 }Nested Objects
Objects can contain other objects as property values. These are called nested objects.
let order = {
orderId: 501,
customer: {
name: "Nisha",
email: "nisha@example.com"
},
item: {
name: "Headphones",
price: 3500
}
};
console.log(order.customer.name); // Nisha
console.log(order.item.price); // 3500Array of Objects
A very common data pattern is an array of objects — used to represent a list of records, like products, students, or employees.
let students = [
{ name: "Ankit", score: 85 },
{ name: "Priya", score: 92 },
{ name: "Rohit", score: 78 }
];
for (let student of students) {
console.log(student.name + " scored " + student.score);
}
// Output:
// Ankit scored 85
// Priya scored 92
// Rohit scored 78Key Points to Remember
- Objects store data as key-value pairs inside curly braces
{ } - Access properties using dot notation
obj.keyor bracket notationobj["key"] - Functions inside objects are called methods
thisinside a method refers to the current objectObject.keys(),Object.values(), andObject.entries()are useful for exploring objects- Use destructuring to extract properties into variables cleanly
- The spread operator
...copies and merges objects - Objects can be nested inside other objects
- Arrays of objects are the most common data pattern in JavaScript applications
