Overview & Purpose
An object in JavaScript is a collection of related key-value pairs. It's the most important data structure in JavaScript.
Think of a real-world object — a product in an online store has multiple properties:
const product = {
id: "LPT-001",
name: "MacBook Pro 14"",
brand: "Apple",
price: 199900,
category: "laptops",
inStock: true,
specs: {
ram: "16GB",
storage: "512GB SSD"
},
tags: ["apple", "laptop", "premium"],
getFormattedPrice: function() {
return "₹" + this.price.toLocaleString("en-IN");
}
};Objects can hold:
Primitive values (strings, numbers, booleans)
Other objects (nested objects)
Arrays
Functions (called methods when inside objects)
Topic Definition
A JavaScript object is:
A collection of properties, each with a key (name) and value
Mutable — properties can be added, changed, deleted
Reference type — variables hold a reference, not a copy
The shape of real-world data — users, products, API responses, configuration
Object vs Array:
| | Object | Array |
|---|---|---|
| **Access** | By name: `user.name` | By index: `users[0]` |
| **Order** | Not guaranteed | Ordered |
| **Best for** | Single entity with properties | List of items |
| **Shape** | `{}` | `[]` |
Real data often combines both: an array of objects ([{id:1}, {id:2}]) is the most common API response format.
Why It Matters
Objects are everywhere in JavaScript:
Every DOM element is an object: document.getElementById('btn')
Every API response is parsed as an object: JSON.parse(data)
Every React component receives an object as props: function Card({ title, price })
Browser storage: localStorage.setItem('user', JSON.stringify(userObj))
Configuration: const options = { method: 'POST', headers: {...}, body: '...' }
Syntax Guide
// ═══════════════════════════════════════════════
// CREATING OBJECTS
// ═══════════════════════════════════════════════
// Object literal (most common)
const user = {
name: "Asha Sharma",
email: "asha@example.com",
age: 28,
city: "Jaipur"
};
// ═══════════════════════════════════════════════
// READING PROPERTIES
// ═══════════════════════════════════════════════
// Dot notation (use when key name is known)
console.log(user.name); // "Asha Sharma"
console.log(user.email); // "asha@example.com"
// Bracket notation (use with dynamic keys)
const field = "city";
console.log(user[field]); // "Jaipur"
console.log(user["age"]); // 28
// ═══════════════════════════════════════════════
// MODIFYING OBJECTS
// ═══════════════════════════════════════════════
user.age = 29; // Update
user.phone = "+91-9876543210"; // Add new property
delete user.city; // Delete property
// ═══════════════════════════════════════════════
// OBJECT WITH METHOD
// ═══════════════════════════════════════════════
const calculator = {
result: 0,
add(n) { this.result += n; return this; },
multiply(n) { this.result *= n; return this; },
getValue() { return this.result; }
};
// Method chaining
const answer = calculator.add(10).multiply(3).getValue();
console.log(answer); // 30- key (property name) — any valid identifier or string. Quoted when it contains spaces or special chars.
- value — any JavaScript value: primitive, array, object, function
- Dot notation (obj.key) — for known, static property names
- Bracket notation (obj['key'] or obj[variable]) — for dynamic/computed property names
- this — inside object methods, refers to the object itself
Accessing a property returns its value, or undefined if the property doesn't exist. Methods return whatever their return statement specifies.
How objects work in memory:
Objects are stored in the heap, and variables hold a reference (pointer) to the object. Two variables can point to the same object:
const obj1 = { name: "Asha" };
const obj2 = obj1; // ⚠️ Same reference!
obj2.name = "Ravi";
console.log(obj1.name); // "Ravi" — obj1 also changed!
// Copy: use spread or Object.assign
const obj3 = { ...obj1 }; // Independent copy
obj3.name = "Priya";
console.log(obj1.name); // "Ravi" — obj1 unchanged ✅Property shorthand (ES6):
const name = "Asha";
const age = 28;
// Old way
const user1 = { name: name, age: age };
// Shorthand (if variable name matches key name)
const user2 = { name, age }; // Same result!Computed property names:
const key = "dynamicField";
const obj = { [key]: "value" }; // { dynamicField: "value" }Runnable Code Examples
Example 1: Object CRUD — Create, Read, Update, Delete
All four fundamental operations on JavaScript objects.
// CREATE
const employee = {
id: "EMP-001",
name: "Asha Sharma",
department: "Engineering",
salary: 85000,
skills: ["JavaScript", "React", "Node.js"],
address: {
city: "Jaipur",
state: "Rajasthan"
}
};
// READ
console.log("Name:", employee.name);
console.log("City:", employee.address.city);
console.log("First skill:", employee.skills[0]);
// UPDATE
employee.salary = 95000;
employee.skills.push("TypeScript");
employee.address.city = "Mumbai";
// ADD new property
employee.joiningDate = "2023-01-15";
// DELETE
delete employee.address;
console.log("\nAfter updates:");
console.log("Salary:", employee.salary);
console.log("Skills:", employee.skills);
console.log("Joining:", employee.joiningDate);
console.log("Address:", employee.address); // undefinedObjects are mutable — properties can be read, updated, added, and deleted. Nested properties are accessed with chained dots. delete removes a property (returns undefined afterwards).
Example 2: Object Destructuring — Extract Properties Cleanly
ES6 destructuring is the modern way to extract multiple properties at once.
const user = {
id: 101,
firstName: "Asha",
lastName: "Sharma",
email: "asha@example.com",
role: "admin",
preferences: {
theme: "dark",
language: "hi"
}
};
// Basic destructuring
const { firstName, email, role } = user;
console.log(firstName, email, role);
// Rename while destructuring
const { firstName: name, role: userRole } = user;
console.log(name, userRole);
// Default values
const { phone = "Not provided", role: userType = "guest" } = user;
console.log(phone, userType);
// Nested destructuring
const { preferences: { theme, language } } = user;
console.log(theme, language);
// In function parameters (very common in React!)
function displayUser({ firstName, role, email }) {
console.log(`${firstName} (${role}) — ${email}`);
}
displayUser(user);Destructuring extracts multiple properties in one line. Renaming: { original: newName }. Defaults: { key = defaultValue }. Nested: { obj: { prop } }. Function parameter destructuring is standard in React for props.
Example 3: Spread, Object.assign, and Copying
Modern ways to copy, merge, and update objects immutably.
const defaults = {
theme: "light",
language: "en",
notifications: true,
pageSize: 10
};
const userPrefs = {
theme: "dark",
language: "hi"
};
// Merge: spread — later properties override earlier ones
const settings = { ...defaults, ...userPrefs };
console.log("Merged settings:", settings);
// Create modified copy (immutable update pattern)
const updatedUser = {
name: "Asha",
email: "asha@example.com",
role: "viewer"
};
const promoted = { ...updatedUser, role: "admin", updatedAt: "2026-06-01" };
console.log("Original role:", updatedUser.role); // viewer
console.log("New role:", promoted.role); // admin
// Combining spread with computed keys
const fieldName = "email";
const dynamicUpdate = { ...updatedUser, [fieldName]: "newemail@example.com" };
console.log("Updated email:", dynamicUpdate.email);Spread creates a shallow copy and merges objects. Later properties override earlier ones. This immutable update pattern (create a new object instead of modifying) is standard in React state management.
Example 4: Objects from API Responses — Real-World Data
How you work with objects in actual applications.
// Simulating an API response
const apiResponse = {
status: "success",
timestamp: "2026-06-01T10:30:00Z",
data: {
user: {
id: 42,
name: "Asha Sharma",
avatar: "/images/asha.jpg",
stats: {
orders: 15,
spent: 125000,
lastOrder: "2026-05-20"
}
}
},
meta: {
page: 1,
total: 1,
perPage: 10
}
};
// Extract needed data
const { data: { user }, meta } = apiResponse;
const { name, stats: { orders, spent } } = user;
console.log("Welcome back,", name);
console.log("Orders:", orders);
console.log("Total spent: ₹" + spent.toLocaleString("en-IN"));
// Object.keys, values, entries for iteration
const statsObj = user.stats;
console.log("\nUser Stats:");
Object.entries(statsObj).forEach(([key, value]) => {
console.log(" ", key + ":", value);
});Real API responses have deeply nested objects. Chained destructuring extracts values cleanly. Object.entries() converts an object to an array of [key, value] pairs for easy iteration.
Real-world Use Cases
- 1
User sessions:
const session = { userId, token, expiresAt, permissions }— all session data in one object. - 2
API request options:
fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) - 3
React component props: Every component receives props as an object:
function Card({ title, description, price, onClick }) - 4
Redux/Zustand state: App state is a large object that gets immutably updated:
{ ...state, cart: [...state.cart, newItem] } - 5
Configuration objects:
const dbConfig = { host: 'localhost', port: 5432, database: 'myapp', ssl: true } - 6
Event objects:
element.addEventListener('click', (event) => console.log(event.target, event.clientX))
Coding Exercises
Exercise Challenge
Build a product object with nested specs. Write a method getDisplayName() that returns 'Apple MacBook Pro 14 (M3, 16GB, 512GB)'.
Practice Tasks Checklist
JavaScript Objects Quiz Challenges
Quiz Challenge
What is the value of `user.address.city` if `user.address` is undefined?
Quiz Challenge
How do you add a new property to an existing object?
Quiz Challenge
What does object destructuring do?
Technical Interview Q&As
1What is the difference between dot notation and bracket notation for object property access?
Model Answer:
Dot notation (obj.key) is cleaner and preferred when the property name is a known, valid identifier. Bracket notation (obj['key'] or obj[variable]) is necessary when: 1) the property name has spaces or special chars ('first name'), 2) the property name is stored in a variable, 3) the property name is computed dynamically. Both access the same properties.2How do you copy an object in JavaScript?
Model Answer:
Shallow copy: `const copy = { ...original }` or `Object.assign({}, original)`. This copies one level deep — nested objects are still shared by reference. Deep copy: `const deep = structuredClone(original)` (modern, handles all types) or `JSON.parse(JSON.stringify(original))` (works for JSON-serializable data). For state management, always use shallow copies unless you specifically need deep copying.3Why is `obj1 === obj2` false even if they look identical?
Model Answer:
Objects are reference types. `===` for objects compares memory addresses (references), not content. `{} === {}` is false because they're two different objects in memory. Only returns true if both variables point to the EXACT same object. To compare content: use JSON.stringify for simple objects, or a library like lodash.isEqual for complex comparisons.4What is object destructuring and when do you use it?
Model Answer:
Destructuring extracts multiple properties into variables in one statement: `const { name, email } = user` is equivalent to `const name = user.name; const email = user.email`. Use it when: extracting multiple properties from an object, in function parameters (`function fn({ name, age })`), renaming (`{ name: displayName }`), and setting defaults (`{ role = 'guest' }`). It's standard in React for props.