|11. Objects in JavaScript
Chapter 11JavaScript Tutorial~1 min read

Objects in JavaScript

Key-Value Pairs — Real World Data Model

Objects म्हणजे key-value pairs मध्ये data store करणे. Real-world entities represent करण्यासाठी — user, product, order — objects perfect आहेत. JavaScript मध्ये arrays, functions, dates सगळे objects आहेत.

Object Create करणे

javascript
// Object Literal Syntax
let person = {
    name: "Rahul Patil",
    age: 25,
    city: "Pune",
    isStudent: false
};

// Keys access करणे
console.log(person.name);      // Dot notation — "Rahul Patil"
console.log(person["age"]);    // Bracket notation — 25

// Dynamic key
let key = "city";
console.log(person[key]);      // "Pune"

Properties Add, Modify, Delete

Object Modification

javascript
let person = { name: "Rahul", age: 25 };

// Modify
person.age = 26;
console.log(person.age); // 26

// Add new property
person.city = "Mumbai";
console.log(person.city); // "Mumbai"

// Delete property
delete person.isStudent;
console.log(person);

Methods — Object मधील Functions

Object Methods

javascript
let calculator = {
    add: function(a, b) {
        return a + b;
    },
    subtract(a, b) {  // Shorthand syntax
        return a - b;
    },
    multiply: (a, b) => a * b  // Arrow function
};

console.log(calculator.add(10, 5));      // 15
console.log(calculator.subtract(10, 4)); // 6
console.log(calculator.multiply(3, 4));  // 12

Nested Objects आणि for...in

Nested Objects + Iteration

javascript
// Nested object
let user = {
    name: "Priya",
    address: {
        city: "Mumbai",
        pin: 400001,
        state: "Maharashtra"
    }
};
console.log(user.address.city); // "Mumbai"

// for...in — सगळे properties iterate करणे
let car = { brand: "Tata", model: "Nexon", year: 2023 };
for (let key in car) {
    console.log(key + ": " + car[key]);
}

Useful Object Methods

Object.keys, values, entries

javascript
let car = { brand: "Toyota", year: 2020, color: "White" };

console.log(Object.keys(car));    // ["brand", "year", "color"]
console.log(Object.values(car));  // ["Toyota", 2020, "White"]
console.log(Object.entries(car)); // [["brand","Toyota"], ["year",2020], ...]

// Object freeze — changes block करणे
Object.freeze(car);
car.year = 2025; // ❌ Silently ignored

Key Points — लक्षात ठेवा

  • Object = key-value pairs — { key: value }
  • Dot notation: obj.key | Bracket: obj["key"]
  • Methods = object मधील functions
  • for...in ने object properties iterate
  • Object.keys() / .values() / .entries() — useful helpers
0/13 chapters पूर्ण