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
- Dot notation:
object.key
- 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"