Skip to the workspace
Pebellslearn by building
Loops and Iterations  ›  Lesson

The for...in Loop

for...in loop 12 min

javascript / The for...in Loop

Explore each scene at your own pace.

01 · The for...in Loop

The for...in Loop

The for...in Loop

for...in visits enumerable string property keys, including inherited enumerable keys. It is not an array-value loop.

Separate the key you received from the value you read using that key.

See the mechanism

Walk through the modelThe for...in LoopAuthored snapshots of the example; use Run below to test the code.
key"title"
for...in provides a string property key.
1 of 3

Follow one example

javascript

key is first a property name such as "title", not its value. article[key] performs the value lookup. Object.hasOwn keeps only the record’s own properties; inherited enumerable keys can also be visited by for...in. For array values, prefer for...of instead of relying on property enumeration.

Predict, change and check

Predict: What would printing article.key read compared with article[key]?

Test your explanation: Print both inside the loop. Then add a property and explain why the loop receives a key string for it rather than a complete key-value pair.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Enumerating keys is not reading list values

for...in enumerates enumerable string-keyed properties, including inherited ones. It does not enumerate symbol keys. An array can also have extra properties, so for...in is generally the wrong choice when the feature needs the array's item values in ordinary list order.

Use Object.keys or Object.entries when you specifically want own enumerable string properties. If inherited values matter, make that choice explicit. Validate a property's presence independently of the truthiness of its value; an own field containing false or zero is still an own field.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.