⚡ Phase 1 · Foundations 🟡 Intermediate MODULE 09

JavaScript Objects

⏱️ 35 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Phase 169%
🎯 What you'll learn: How to create and work with JavaScript objects — the foundation of almost every JS program. You'll master object literals, dot and bracket notation, methods, this, destructuring, spread, JSON, optional chaining, and Object utility methods.

Object Literals & Property Access

An object is a collection of key-value pairs. Keys are strings (or Symbols), and values can be any data type.

Creating Objects & Accessing Properties
JS
// Object literal
const user = {
  name: 'Ali',
  age: 25,
  email: 'ali@example.com',
  isAdmin: false
};

// Dot notation (preferred when key is known)
user.name;         // 'Ali'
user.age;          // 25

// Bracket notation (when key is dynamic)
user['email'];     // 'ali@example.com'
const key = 'age';
user[key];         // 25

// Add new properties
user.city = 'Lahore';

// Delete a property
delete user.isAdmin;

// Check if property exists
'name' in user;   // true
user.hasOwnProperty('city'); // true

Methods & The this Keyword

Object methods are functions stored as property values. Inside a method, this refers to the object the method belongs to.

Object Methods & this
JS
const person = {
  name: 'Sara',
  age: 28,
  // Method using regular function (this works!)
  greet() {
    return `Hello, I'm ${this.name}!`;
  },
  getInfo() {
    return `${this.name} is ${this.age} years old.`;
  },
  haveBirthday() {
    this.age++;
    return `Happy birthday! Now ${this.age}`;
  }
};

person.greet();       // "Hello, I'm Sara!"
person.haveBirthday(); // "Happy birthday! Now 29"

// WARNING: Arrow functions don't have their own 'this'
const bad = {
  name: 'Test',
  greet: () => `Hello ${this.name}`  // this is undefined!
};
⚠️
Arrow functions and this
Never use arrow functions as object methods when you need this. Arrow functions inherit this from their lexical scope (the enclosing context), not the object. Use regular function syntax method() {} instead.

Destructuring & Spread

Object Destructuring & Spread
JS
const product = {
  id: 42,
  name: 'Keyboard',
  price: 75,
  brand: 'Logitech'
};

// Basic destructuring
const { name, price } = product;
// name='Keyboard', price=75

// Rename while destructuring
const { name: productName, price: cost } = product;
// productName='Keyboard', cost=75

// Default values
const { inStock = true } = product;
// inStock=true (not in object, uses default)

// Rest in destructuring
const { id, ...rest } = product;
// id=42, rest={name,price,brand}

// Spread to copy/merge objects
const copy = { ...product };
const updated = { ...product, price: 65, sale: true };

// Spread in function parameter
function displayProduct({ name, price, brand = 'Unknown' }) {
  return `${name} by ${brand} — $${price}`;
}

Object Utility Methods

Object.keys, values, entries & more
JS
const scores = { ali: 85, sara: 92, bilal: 78 };

// Get all keys
Object.keys(scores);     // ['ali','sara','bilal']

// Get all values
Object.values(scores);   // [85, 92, 78]

// Get [key, value] pairs
Object.entries(scores);  // [['ali',85],['sara',92],['bilal',78]]

// Iterate with entries
Object.entries(scores).forEach(([name, score]) => {
  console.log(`${name}: ${score}`);
});

// Convert entries back to object
const doubled = Object.fromEntries(
  Object.entries(scores).map(([k, v]) => [k, v * 2])
);

// Computed property names
const field = 'username';
const dynamic = { [field]: 'ali123' };  // {username:'ali123'}

// Object.assign — merge (mutates target)
const merged = Object.assign({}, scores, {hina: 95});

JSON & Optional Chaining

JSON.stringify, JSON.parse, Optional Chaining
JS
// JSON — JavaScript Object Notation
const user = { name: 'Ali', age: 25, hobbies: ['coding', 'reading'] };

// Convert object to JSON string
const json = JSON.stringify(user);
// '{"name":"Ali","age":25,"hobbies":["coding","reading"]}'

// Pretty-print JSON
JSON.stringify(user, null, 2);

// Parse JSON string back to object
const parsed = JSON.parse(json);

// Deep clone using JSON (simple objects only)
const clone = JSON.parse(JSON.stringify(user));

// Optional chaining (?.) — safe property access
const profile = {
  name: 'Sara',
  address: { city: 'Karachi', zip: 75500 }
};

profile?.address?.city;    // 'Karachi'
profile?.phone?.number;    // undefined (no error!)
profile?.getAge?.();       // undefined (safe method call)

// Nullish coalescing (??) — fallback value
profile?.phone?.number ?? 'N/A';  // 'N/A'

Real-World: User Profile & Product Catalog

Product Catalog with Object Methods
JS
const catalog = {
  products: [
    {id:1, name:'Laptop', price:1200, category:'electronics'},
    {id:2, name:'Desk', price:350, category:'furniture'},
    {id:3, name:'Headphones', price:150, category:'electronics'}
  ],

  getByCategory(category) {
    return this.products.filter(p => p.category === category);
  },

  getById(id) {
    return this.products.find(p => p.id === id);
  },

  getTotalValue() {
    return this.products.reduce((sum, p) => sum + p.price, 0);
  },

  addProduct(product) {
    this.products.push({ ...product, id: this.products.length + 1 });
  }
};

catalog.getByCategory('electronics'); // [Laptop, Headphones]
catalog.getTotalValue();                 // 1700
🧩 Knowledge Check — Objects
5 questions to test your JS objects knowledge.
1. What does Object.entries(obj) return?
2. Inside an object method, what does this refer to?
3. What does optional chaining ?. do?
4. Which syntax correctly destructures and renames a property?
5. What is JSON.parse(JSON.stringify(obj)) commonly used for?
📚
Challenge — Student Grade Book
Build a grade tracking system using objects · Intermediate
Build a Student Grade Book

Create a gradebook.js file with a gradeBook object:

1. Store students as objects with name, grades array, subject
2. addStudent(name, subject) — add new student with empty grades
3. addGrade(name, grade) — push grade to student's array
4. getAverage(name) — calculate average using reduce
5. getLetterGrade(name) — A(90+), B(80+), C(70+), D(60+), F
6. getTopStudents(n) — return top n students sorted by average
7. getSummary() — return Object with class stats: avg, highest, lowest
💡 Show hints
  • Store students as an array of objects inside gradeBook
  • Use this.students.find(s => s.name === name) to look up students
  • Average: grades.reduce((a,b) => a+b, 0) / grades.length
  • Use spread + sort for top students: [...this.students].sort(...)
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 9 Complete!

Objects mastered! You now understand the core data structure of JavaScript. Next: DOM Manipulation!

Module 09 of 13Phase 1 — JS Foundations