Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.4 — Looping Over Objects
JavaScript · Example 3 of 4

for...in sees inherited keys

Object.create(base) makes an object whose prototype is base (Phase 7.3). for...in walks up to it; Object.keys doesn't.

Objects aren't directly loopable with for...of, so you turn them into arrays first: Object.keys for names, Object.values for values, Object.entries for [key, value] pairs; Object.fromEntries turns pairs back into an object.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given const stock = { pens: 12, books: 0, bags: 3, rulers: 0 }, log an array of the names of items that are out of stock.

02

Write invert(obj) that swaps keys and values: invert({ a: "x", b: "y" }) returns { x: 'a', y: 'b' }.

03

Given an array of fruit names with repeats, build an object counting each fruit, then log the total number of fruits using Object.values.

Explain it without notes

01

Why can't you use for...of directly on a plain object, and what do you use instead?

02

What do Object.keys, Object.values and Object.entries return, and what do they leave out?

03

How do you filter or transform an object's properties?

04

What's the difference between for...in and Object.keys?

for...in sees inherited keys

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

for...in: own
for...in: shared
Object.keys: [ 'own' ]
own only: own