JavaScript Roadmap — Day 15: Objects — Complete Guide

 

JavaScript · Day 15 of 180 · Beginner Phase

Objects — Complete Guide

Objects are the foundation of JavaScript. Everything in JS is an object. Every API response is an object. Every React component uses objects. Master objects and you master the language itself.

Day 15 / 180
Beginner Phase
🕐 14 min read
💻 7 code examples
🎯 3 practice tasks

Every time you sign up for a website — your data is stored as an object:

Real world — your data as an object
const user = {
  id:        1,
  name:      "Muhammad Waheed",
  email:     "waheed@gmail.com",
  city:      "Faisalabad",
  isActive:  true,
  skills:    ["JavaScript", "React", "Node.js"],
  joinedAt:  "2026-03-01"
};

That is an object. Every user in every app you build will look exactly like this. Every API response you receive will be an object. Objects are not just a JavaScript concept — they are the universal language of data on the web. JSON stands for JavaScript Object Notation — the entire web uses this format. Master objects today and everything else becomes easier.

1. What is an Object?

An object is a collection of key-value pairs. The key is always a string (or symbol) and the value can be anything — a number, string, array, function, or even another object. Think of it like a labeled storage box — each label is a key and the content inside is the value:

JavaScript — Object Structure
// Object literal — most common way to create
const developer = {
  // key    : value
  name      : "Waheed",         // string
  age       : 22,               // number
  isHired   : false,            // boolean
  skills    : ["JS", "React"], // array
  address   : {                  // nested object
    city    : "Faisalabad",
    country : "Pakistan"
  },
  greet     : function() {       // method (function)
    return `Hi I am ${this.name}`;
  }
};

console.log(developer.name);          // "Waheed"
console.log(developer.address.city);   // "Faisalabad"
console.log(developer.greet());        // "Hi I am Waheed"

2. Access Object Properties

There are two ways to access object properties — dot notation and bracket notation. Each has its use case:

JavaScript — Accessing Properties
const user = {
  name    : "Waheed",
  age     : 22,
  city    : "Faisalabad",
  "full-name": "Muhammad Waheed"  // key with hyphen
};

// Dot notation — most common
console.log(user.name);  // "Waheed"
console.log(user.age);   // 22

// Bracket notation — for dynamic keys
console.log(user["name"]);      // "Waheed"
console.log(user["full-name"]); // "Muhammad Waheed"

// Dynamic key — variable as key
const key = "city";
console.log(user[key]); // "Faisalabad"

// Access nested object
const profile = {
  user: {
    address: {
      city: "Faisalabad"
    }
  }
};
console.log(profile.user.address.city);    // "Faisalabad"
console.log(profile?.user?.address?.city);  // safe with ?.

// Non-existent property — undefined not error
console.log(user.salary); // undefined

3. Add, Update & Delete Properties

Objects are mutable by default — you can add, update, and delete properties at any time. Understanding this is critical for working with real application data:

JavaScript — Modify Objects
const user = { name: "Waheed", age: 22 };

// Add new property
user.city   = "Faisalabad";
user.salary = 150000;
console.log(user);
// { name:"Waheed", age:22, city:"Faisalabad", salary:150000 }

// Update existing property
user.age    = 23;
user.salary = 200000;
console.log(user.age);    // 23
console.log(user.salary); // 200000

// Delete property
delete user.salary;
console.log(user.salary); // undefined

// Check if property exists
console.log("name" in user);   // true
console.log("salary" in user); // false — deleted

// hasOwnProperty — check own vs inherited
console.log(user.hasOwnProperty("name")); // true

4. Object Methods — Functions Inside Objects

When a function lives inside an object it is called a method. Methods use this to refer to the object they belong to. This is how objects encapsulate both data and behavior:

JavaScript — Object Methods
const bankAccount = {
  owner:   "Waheed",
  balance: 50000,

  // ES6 shorthand method syntax
  deposit(amount) {
    this.balance += amount;
    console.log(`Deposited Rs${amount}. Balance: Rs${this.balance}`);
  },

  withdraw(amount) {
    if (amount > this.balance) {
      console.log("Insufficient balance!");
      return;
    }
    this.balance -= amount;
    console.log(`Withdrawn Rs${amount}. Balance: Rs${this.balance}`);
  },

  getBalance() {
    return `Rs${this.balance}`;
  }
};

bankAccount.deposit(10000);   // Deposited Rs10000. Balance: Rs60000
bankAccount.withdraw(5000);  // Withdrawn Rs5000. Balance: Rs55000
bankAccount.withdraw(99999); // Insufficient balance!
console.log(bankAccount.getBalance()); // Rs55000

5. Destructuring — Extract Properties Cleanly 🔥

Object destructuring lets you extract multiple properties into variables in one line. This is used everywhere in modern JavaScript — especially in React for props and API responses:

JavaScript — Object Destructuring
const developer = {
  name:       "Waheed",
  age:        22,
  city:       "Faisalabad",
  salary:     150000,
  skills:     ["JavaScript", "React"]
};

// Basic destructuring
const { name, age, city } = developer;
console.log(name, age, city); // "Waheed" 22 "Faisalabad"

// Rename while destructuring
const { name: devName, salary: devSalary } = developer;
console.log(devName, devSalary); // "Waheed" 150000

// Default values
const { name: n, experience = 0 } = developer;
console.log(experience); // 0 — not in object

// Nested destructuring
const user = { address: { city: "Lahore", zip: "54000" } };
const { address: { city: userCity, zip } } = user;
console.log(userCity, zip); // "Lahore" "54000"

// In function parameters — most common React pattern
function showProfile({ name, city, salary = 0 }) {
  console.log(`${name} | ${city} | Rs${salary}`);
}
showProfile(developer); // Waheed | Faisalabad | Rs150000

6. Spread Operator & Object.assign

Copying and merging objects is a daily task in real applications. The spread operator is the modern, clean way to do it — and it is used constantly in React state management:

JavaScript — Spread & Object.assign
const user = { name: "Waheed", age: 22 };

// Copy object — spread
const copy = { ...user };
copy.age = 25;
console.log(user.age); // 22 — original unchanged ✅
console.log(copy.age); // 25

// Merge two objects
const defaults = { theme: "dark", lang: "en", fontSize: 14 };
const userPrefs = { theme: "light", lang: "ur" };

const settings = { ...defaults, ...userPrefs };
console.log(settings);
// { theme:"light", lang:"ur", fontSize:14 }
// userPrefs overwrites defaults where they overlap

// Update one property immutably — React pattern
const updatedUser = { ...user, age: 23, city: "Lahore" };
console.log(updatedUser);
// { name:"Waheed", age:23, city:"Lahore" }

// Object.assign — older way, same result
const merged = Object.assign({}, defaults, userPrefs);
console.log(merged); // same as spread
Pro Tip #1 — Spread for immutable updates
In React you should never directly mutate state objects. Always use spread to create a new object with the updated value — setState({ ...oldState, newProp: newValue }). This is one of the most used patterns in all of React development.
Pro Tip #2 — Later properties override earlier ones
When spreading two objects with the same key — the later one wins. { ...defaults, ...userPrefs } means userPrefs values override defaults. This is how settings systems and configuration merging works in every application.
Pro Tip #3 — Spread is shallow copy only
Spread only copies one level deep. If your object has nested objects — those nested references are still shared. For deep cloning use JSON.parse(JSON.stringify(obj)) or a library like lodash. This is a very common source of bugs in React applications.

7. Built-in Object Methods — Essential Tools

JavaScript provides powerful built-in methods on the Object class for working with object data. These are used constantly in real applications for iterating over data from APIs:

JavaScript — Object Built-in Methods
const developer = {
  name:   "Waheed",
  age:    22,
  city:   "Faisalabad",
  salary: 150000
};

// Object.keys() — array of keys
console.log(Object.keys(developer));
// ["name", "age", "city", "salary"]

// Object.values() — array of values
console.log(Object.values(developer));
// ["Waheed", 22, "Faisalabad", 150000]

// Object.entries() — array of [key, value] pairs
console.log(Object.entries(developer));
// [["name","Waheed"], ["age",22], ...]

// Loop with Object.entries()
for (const [key, value] of Object.entries(developer)) {
  console.log(`${key}: ${value}`);
}

// Object.freeze() — prevent all changes
const config = Object.freeze({ apiUrl: "https://api.waheedblog.online" });
config.apiUrl = "changed"; // silently ignored!
console.log(config.apiUrl); // "https://api.waheedblog.online"

// Convert entries back to object
const entries = [["name", "Waheed"], ["age", 22]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: "Waheed", age: 22 }

8. Try It Yourself

Edit the code and click Run Code. Try destructuring, spreading and using Object methods!

✏️ Try it Yourself — Objects
OUTPUT
// Click Run Code to see output
💡 Edit the code and click Run!

9. Practice Tasks

Task 1 — Easy: Your Developer Profile

Create a profile object with your name, age, city, skills array, and a introduce() method that returns a full introduction sentence. Use this inside the method. Call the method and log the result. Then use Object.keys() to list all your profile properties.

Task 2 — Medium: Settings Manager

Create a defaultSettings object with theme, language, fontSize, and notifications. Create a userSettings object that only overrides theme and language. Use spread to merge them into finalSettings. Then write a function updateSetting(settings, key, value) that returns a new object with the updated value — without mutating the original.

Task 3 — Hard: Mini User Database

Create an array of 5 user objects. Write these functions using Object methods and array methods together: getUserNames() — returns array of all names. findByCity(city) — returns all users from that city. getSalarySummary() — returns object with total, average, highest, lowest salary. Use Object.entries() to display the summary nicely.

Next Lesson
Day 16 — DOM Manipulation
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts