JavaScript Objects

📚 Lesson 11 of 22  •  ⏱ 12 min read  •  Beginner

Creating Objects

JavaScript
// Object literal — most common way
const student = {
  name: "Priya",
  age: 22,
  course: "Computer Science",
  active: true
};

// Access with dot notation
student.name   // "Priya"

// Access with bracket notation (needed for dynamic keys)
student["age"]  // 22

const key = "course";
student[key]   // "Computer Science"

Add, Modify & Delete

JavaScript
const car = { brand: "Maruti", year: 2020 };

// Add new property
car.color = "white";

// Modify
car.year = 2023;

// Delete
delete car.color;

// Check if property exists
"brand" in car       // true
"price" in car       // false
car.price !== undefined  // false

Methods (Functions in Objects)

JavaScript
const calculator = {
  value: 0,

  // Method shorthand (ES6)
  add(n)      { this.value += n; return this; },
  subtract(n) { this.value -= n; return this; },
  result()    { return this.value; }
};

// Method chaining
calculator.add(10).add(5).subtract(3).result();  // 12

Property Shorthand

JavaScript
const name = "Kumar";
const age  = 25;

// Without shorthand
const user = { name: name, age: age };

// With shorthand (when key name = variable name)
const user = { name, age };  // same result

// Computed property names
const field = "email";
const profile = { [field]: "kumar@example.com" };
// { email: "kumar@example.com" }

Object.keys, values, entries

JavaScript
const marks = { math: 85, science: 92, english: 78 };

Object.keys(marks)    // ["math", "science", "english"]
Object.values(marks)  // [85, 92, 78]
Object.entries(marks) // [["math",85], ["science",92], ["english",78]]

// Iterate
for (const [subject, mark] of Object.entries(marks)) {
  console.log(`${subject}: ${mark}`);
}

// Average
const avg = Object.values(marks).reduce((s, m) => s + m, 0) / Object.keys(marks).length;

Object Spread — Copy & Merge

JavaScript
const defaults = { theme: "dark", fontSize: 16, lang: "en" };
const userPrefs = { fontSize: 18, lang: "ta" };

// Merge — later keys overwrite earlier ones
const settings = { ...defaults, ...userPrefs };
// { theme:"dark", fontSize:18, lang:"ta" }

// Add new properties to a copy
const updated = { ...student, age: 23 };  // original unchanged