Objects inside objects
Real data nests. A student has grades, grades have subjects:
const student = { name: "Ada", grades: { math: 95, cs: 99 } }; console.log(student.grades.math); // 95
Chain the dots one level at a time. If a middle link might be missing, student.grades?.math answers undefined instead of crashing (the optional chaining operator ?.).
Looping over properties
Objects are not directly for...of iterable. Instead, three helpers turn an object into an array first:
Object.keys(obj)→ array of key stringsObject.values(obj)→ array of valuesObject.entries(obj)→ array of[key, value]pairs
With entries you can unpack each pair right in the loop header, like Python's for k, v in d.items():
for (const [subject, grade] of Object.entries(student.grades)) { console.log(`${subject}: ${grade}`); }
The [subject, grade] part is called destructuring: it splits a two-item array into two named variables.
Code exercise · javascript
Run it. Chained dots reach into the nest, Object.entries feeds the loop, and Object.keys shows the top-level property names.
Code exercise · javascript
Your turn. Loop over the prices object with Object.entries and print one line per item in the form: coffee costs $3
Code exercise · javascript
Second practice. Total the cart: Object.values gives you just the prices, and a for...of loop (lesson 3-3) adds them into total. Print the result.
Quiz
Which call gives you an array of [key, value] pairs, like Python's dict.items()?