🧱 JavaScript Objects

Last Updated: 15th October 2025


Objects store data in key–value pairs.
Each key (called a property) has a value (which can be a number, string, array, or even another object).

Hinglish Tip 🗣: Object ek dabba (box) hota hai jisme “name–value” ke pairs rakhe jaate hain. Example — Aadhaar card me name, age, address.


📦 Creating an Object

1. Using Object Literal (Most Common)

const person = {
  name: "Sadhu",
  age: 2,
  city: "Kashi",
};

2. Using Object Constructor

const person = new Object();
person.name = "Sadhu";
person.age = 2;
person.city = "Kashi";

🗝Accessing Object Properties

You can access values using:

  • Dot Notation → object.key
  • Bracket Notation → object["key"]
console.log(person.name); // Sadhu
console.log(person["name"]); // Sadhu

Hinglish Tip 🗣: Jab key ka naam variable ya space wale words me ho to [] ka use karo.


📝 Updating And Delete Properties

You can change or add new key–value pairs anytime.

person.age = 1; // update
person.country = "India"; // add

Use the delete keyword:

delete person.country; // delete

Nested Object

Object inside another Object

const person = {
  name: "Sadhu",
  age: 2,
  address: {
    city: "Kashi",
    state: "Uttar Pradesh",
  },
};

Object Destructuring

It Means extracting data from an object and assigning it to a variable.

const person = {
  name: "Sadhu",
  age: 2,
  address: {
    city: "Kashi",
    state: "Uttar Pradesh",
  },
};

const { name, age } = person;
console.log(name); // Sadhu
console.log(age); // 2

Spread Operator with Objects

Example 1: Copy Object

const user = { name: "Amit", age: 25 };
const copiedUser = { ...user };
console.log(copiedUser);

Example 2: Merge Objects

const user = { name: "Amit", age: 25 };
const extra = { city: "Delhi" };
const newUser = { ...user, ...extra };
console.log(newUser);

Hinglish Tip 🗣: Agar dono objects me same key hai, to last wala value overwrite kar deta hai.

Example 3: Add or Update Properties

const student = { name: "Karan", grade: "A" };

const updated = { ...student, grade: "A+", passed: true };
console.log(updated);

Methods Chaining

const person = {
  name: "Sadhu",
  age: 2,
  address: {
    city: "Kashi",
    state: "Uttar Pradesh",
  },
};

const city = person.address.city;
console.log(city); // Kashi

💡 Quick Practice

  • Create an object book with title, author, and price.
  • Add a new key publisher.
  • Update the price.
  • Delete the author property.
  • Print the final object.
  • Exercise Set 1
  • Exercise Set 2