JavaScript Tutorial in Hindi #20 | Mastering Objects in JS (2025)

βœ… 1. What is an Object in JavaScript?

An object is a collection of key-value pairs. It can store data like strings, numbers, arrays, functions, and even other objects.

js
CopyEdit
let person = {
name: "Mohit",
age: 30,
isStudent: false
};

βœ… 2. How to Create an Object

js
CopyEdit
let car = {
brand: "Toyota",
model: "Fortuner",
year: 2024
};

βœ… 3. Accessing Object Properties

  1. Dot notation: object.key
  2. Bracket notation: object["key"]
js
CopyEdit
console.log(car.brand); // "Toyota"
console.log(car["model"]); // "Fortuner"

βœ… 4. Adding, Updating & Deleting Properties

πŸ”Ή Add:

js
CopyEdit
car.color = "Black";

πŸ”Ή Update:

js
CopyEdit
car.year = 2025;

πŸ”Ή Delete:

js
CopyEdit
delete car.model;

βœ… 5. Nested Objects & Arrays of Objects

js
CopyEdit
let user = {
name: "Alice",
address: {
city: "Delhi",
zip: 110001
},
hobbies: ["Reading", "Coding"]
};

console.log(user.address.city); // "Delhi"
console.log(user.hobbies[1]); // "Coding"

βœ… 6. Looping through Objects

πŸ”Ή for...in loop:

js
CopyEdit
for (let key in user) {
console.log(key, user[key]);
}

πŸ”Ή Object.keys(), Object.values(), Object.entries()

js
CopyEdit
console.log(Object.keys(user)); // ["name", "address", "hobbies"]

βœ… 7. Object Destructuring

Extract values directly into variables:

js
CopyEdit
let { name, address } = user;
console.log(name); // "Alice"
console.log(address.city); // "Delhi"

βœ… 8. Spread Operator & Object Merging

πŸ”Ή Spread operator (...) creates a copy or merges objects:

js
CopyEdit
let extra = { age: 25 };
let merged = { ...user, ...extra };
console.log(merged);

βœ… 9. Optional Chaining (?.) & Nullish Coalescing (??)

πŸ”Ή Optional Chaining: Avoid errors if a property doesn’t exist.

js
CopyEdit
console.log(user.address?.city); // "Delhi"
console.log(user.job?.title); // undefined (no error)

πŸ”Ή Nullish Coalescing: Provide fallback for null or undefined.

js
CopyEdit
let name = null;
console.log(name ?? "Guest"); // "Guest"