Intermediate · JavaScript in depth · topic 30 of 64 · 35 min
Objects in depth
Explanation
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.
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)Changing, adding and deleting keys
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); // falseMethods and this
const cart = {
items: 3,
total: 450,
summary() {
return `${this.items} items, Rs ${this.total}`;
},
};
console.log(cart.summary()); // '3 items, Rs 450'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
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); // 253Nested objects and optional chaining
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 undefinedDestructuring, shorthand and computed keys
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' }Copying and merging with spread
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'!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)); // 147Watch 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)
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.
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 }.
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
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.