Skip to content

Intermediate · JavaScript in depth · topic 30 of 64 · 35 min

Objects in depth

Explanation

An object groups related values under names called keys, like a student with a name, a class and marks. You read and change values with dot or bracket notation, loop over them with Object.keys, Object.values and Object.entries, and pull values out with destructuring. Spread makes a copy of an object, but only a shallow one.

What an object is

An object is a set of key and value pairs inside curly braces { }. A key is a name, and its value can be anything: a number, a string, an array, a function or even another object. You used small objects in JavaScript basics (a product with a name and a price). Now we go deeper.

Think of it like this: An object is like a filled-in admission form. Each line has a label printed on it (the key), and what you wrote next to it (the value): Name: Priya. Class: 10. City: Indore. The form keeps all the facts about one student together.
javascript
const student = {
  name: 'Priya',
  class: 10,
  city: 'Indore',
  'roll no': 27,
};
console.log(student.name);       // 'Priya'  (dot notation)
console.log(student['city']);    // 'Indore' (bracket notation)
const key = 'class';
console.log(student[key]);       // 10  (the key is in a variable)
console.log(student['roll no']); // 27  (a key with a space needs brackets)
console.log(student.phone);      // undefined (no such key)
Use dot notation normally; use brackets when the key is in a variable or has spaces

Changing, adding and deleting keys

javascript
const student = { name: 'Priya', marks: 82 };
student.marks = 88;        // update a value
student.city = 'Indore';   // add a new key
delete student.marks;      // remove a key
console.log('city' in student);  // true
console.log('marks' in student); // false
The in operator asks: does this object have this key? (const only stops you pointing student at a different object; the keys can still change)

Methods and this

javascript
const cart = {
  items: 3,
  total: 450,
  summary() {
    return `${this.items} items, Rs ${this.total}`;
  },
};
console.log(cart.summary()); // '3 items, Rs 450'
A function inside an object is a method; this means the object before the dot

Write methods in the short form summary() { }. When you call cart.summary(), this inside it is cart, so this.items reads cart.items. Arrow functions do not get their own this, so do not use them for methods that need this. You will see why in the scope topic.

Looping over an object

javascript
const marks = { maths: 90, science: 85, english: 78 };
Object.keys(marks);    // ['maths', 'science', 'english']
Object.values(marks);  // [90, 85, 78]
Object.entries(marks); // [['maths', 90], ['science', 85], ['english', 78]]

for (const [subject, score] of Object.entries(marks)) {
  console.log(subject + ': ' + score);
}
const total = Object.values(marks).reduce((sum, m) => sum + m, 0); // 253
Turn an object into arrays, then use the array tools you already know

Nested objects and optional chaining

javascript
const user = {
  name: 'Arjun',
  address: { city: 'Chennai', pin: '600001' },
};
console.log(user.address.city); // 'Chennai'
console.log(user.office?.city); // undefined, no crash
// user.office.city would throw: Cannot read properties of undefined
?. stops safely when the part on its left is null or undefined

Destructuring, shorthand and computed keys

javascript
const order = { id: 'A101', amount: 499, status: 'paid' };
const { id, amount } = order;          // two new variables
const { status: orderStatus } = order; // take status, call it orderStatus
const { coupon = 'NONE' } = order;     // default when the key is missing

function label({ id, amount }) {       // destructure a parameter
  return id + ' - Rs ' + amount;
}

const name = 'Kavya';
const age = 21;
const person = { name, age };          // shorthand for { name: name, age: age }

const field = 'city';
const place = { [field]: 'Pune' };     // computed key: { city: 'Pune' }
Destructuring pulls values out; shorthand and [key] build objects quickly

Copying and merging with spread

javascript
const defaults = { theme: 'light', lang: 'en' };
const saved = { lang: 'hi' };
const settings = { ...defaults, ...saved }; // { theme: 'light', lang: 'hi' }

const a = { name: 'Ravi', address: { city: 'Pune' } };
const b = { ...a };
b.name = 'Ravi K';         // a.name is still 'Ravi'
b.address.city = 'Mumbai'; // a.address.city is ALSO 'Mumbai'!
When keys repeat, the later one wins
Careful: Spread makes a shallow copy: only the top level is copied. Nested objects and arrays are still shared between the copy and the original. For a full (deep) copy, use structuredClone, which you will meet in the JSON topic.
Tip: Objects are compared by reference, not by contents. { a: 1 } === { a: 1 } is false, because these are two different objects. Two variables are equal only when they point to the very same object.
javascript
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
  withGst(rate) {
    return Math.round(this.price * (1 + rate / 100));
  }
}
const tea = new Product('Tea 250g', 140);
console.log(tea.withGst(5)); // 147
Classes, briefly: a class is a factory for many objects of the same shape. You will meet them in libraries; plain objects are enough for most front-end work

Watch the lesson

Objects in depth · 1/7

const student = { name: 'Priya', class: 10 };

An object keeps related facts together, as key and value pairs.

Prefer a video by a teacher? Find free videos on “javascript objects destructuring spread optional chaining tutorial” on YouTube ↗

In real life: A food order on a delivery app

When you order food on a delivery app, the order is one object: { id, restaurant: { name, area }, items: [...], charges: { delivery: 30, packaging: 15, gst: 42 }, status }. The app reads order.restaurant.name for the header, loops over Object.entries(order.charges) to show each bill line, and when the order arrives it makes a new object with { ...order, status: "delivered" } instead of editing the old one.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function priceOf(menu, item) that returns the price of item from the menu object, or 0 if the item is not on the menu. The item name is in a variable, so you need bracket notation. Example: priceOf({ chai: 15, samosa: 20 }, "samosa") returns 20, and priceOf({ chai: 15 }, "dosa") returns 0.

Task 2 · Code · Javascript

Write a function addItem(cart, name) that returns a NEW cart object where the count for name is one more than before (start from 0 if it is not there yet). Do not change the original cart: copy it with spread. Example: addItem({ chai: 2 }, "samosa") returns { chai: 2, samosa: 1 }, and addItem({ chai: 2 }, "chai") returns { chai: 3 }.

Task 3 · Code · Javascript

Write a function topSubject(marks) that returns the name of the subject with the highest marks. marks is an object like { maths: 90, science: 95, english: 78 }, so topSubject returns "science". Use Object.entries. For an empty object, return null.

Quick quiz

Question 1

1.const key = 'city'; Which line reads the city of user?

Question 2

2.What does Object.entries({ a: 1, b: 2 }) return?

Question 3

3.const user = { name: 'Asha' }; What is user.address?.city?

Question 4

4.const a = { info: { city: 'Pune' } }; const b = { ...a }; b.info.city = 'Goa'; What is a.info.city now?

Question 5

5.const { price = 100 } = { name: 'Pen' }; What is price?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Transitions and animations