JavaScript Guide
Beginner14 minsJS Tutorial

JavaScript Objects

Complete guide to JavaScript objects — creating, reading, updating, methods, destructuring, spread, and real-world data patterns.

Lesson session

0% complete

0/5
Learn mode

Read the concept first, then inspect syntax and examples.

Study prompt

Current mode guidance

Read the concept first, then inspect syntax and examples.

Confidence

Track your comfort

55%
NewClear

Quick notes

0/240 characters

Concept switcher

Move through the idea before the code.

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)

Example preview

Run it in your head

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); // undefined
Output

Predict the output first, then reveal it.

Next useful links

Related pages from the same JavaScript guide.

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

javascript
// ═══════════════════════════════════════════════
// 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
Reference API Specifications
Parameters:
  • 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
Return Value:

Accessing a property returns its value, or undefined if the property doesn't exist. Methods return whatever their return statement specifies.

Syntax Explanation:

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.

javascript
// 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); // undefined
expected console output
Name: Asha Sharma City: Jaipur First skill: JavaScript After updates: Salary: 95000 Skills: ["JavaScript", "React", "Node.js", "TypeScript"] Joining: 2023-01-15 Address: undefined
Breakdown:

Objects 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.

javascript
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);
expected console output
Asha asha@example.com admin Asha admin Not provided admin dark hi Asha (admin) — asha@example.com
Breakdown:

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.

javascript
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);
expected console output
Merged settings: { theme: 'dark', language: 'hi', notifications: true, pageSize: 10 } Original role: viewer New role: admin Updated email: newemail@example.com
Breakdown:

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.

javascript
// 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);
});
expected console output
Welcome back, Asha Sharma Orders: 15 Total spent: ₹1,25,000 User Stats: orders: 15 spent: 125000 lastOrder: 2026-05-20
Breakdown:

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

1

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

1Create a complete `order` object with nested customer and items data.
2Write a function that merges user settings with defaults using spread.
3Destructure a deeply nested API response to extract specific values.
4Use Object.entries() to render all properties of a settings object.
5Write a function that returns a new object with one property updated (immutable update).
6Create an object with methods that use `this` to access other properties.
7Compare two objects for deep equality without a library.
8Convert an array of [key, value] tuples to an object using Object.fromEntries.
9Use optional chaining to safely access properties 3 levels deep.
10Build a simple reducer function: takes state object + action, returns new state object.

JavaScript Objects Quiz Challenges

1

Quiz Challenge

What is the value of `user.address.city` if `user.address` is undefined?

2

Quiz Challenge

How do you add a new property to an existing object?

3

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.

Related Lessons

Frequently Asked Questions