Bird
Raised Fist0
Javascriptprogramming~10 mins

Iterating over objects in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Iterating over objects
Start with object
↓
Get keys or entries
↓
Loop over keys/entries
↓
Access value for each key
↓
Use key and value
↓
Repeat until all keys done
↓
End
We start with an object, get its keys or entries, loop over them, access each value, and use them until all keys are processed.
Execution Sample
Javascript
const obj = {a: 1, b: 2};
for (const key in obj) {
  console.log(key, obj[key]);
}
This code loops over each key in the object and prints the key and its value.
Execution Table
Stepkeyobj[key]ActionOutput
1a1Access obj['a']Print 'a 1'
2b2Access obj['b']Print 'b 2'
3--No more keysLoop ends
💡 All keys in the object have been iterated, loop ends.
Variable Tracker
VariableStartAfter 1After 2Final
key-ab-
obj[key]-12-
Key Moments - 2 Insights
Why does the loop use 'key' to access the value as obj[key] instead of obj.key?
Because 'key' is a variable holding the property name as a string, we must use bracket notation obj[key] to access the value dynamically. Dot notation obj.key looks for a property literally named 'key'. See execution_table steps 1 and 2.
Does the for...in loop guarantee the order of keys?
No, the for...in loop iterates over keys but the order is not guaranteed. It depends on the JavaScript engine. See execution_table where keys appear in order 'a', then 'b', but this is not always the case.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'key' at step 2?
Aa
Bobj
Cb
Dundefined
💡 Hint
Check the 'key' column in execution_table row for step 2.
At which step does the loop end according to the execution_table?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look for the row where 'No more keys' is the action.
If we replace 'for...in' with 'Object.keys(obj).forEach', how would the iteration change?
AIt would iterate over values directly without keys.
BIt would iterate over keys in the same order but keys are accessed via callback parameter.
CIt would not iterate at all.
DIt would iterate over keys but skip some keys.
💡 Hint
Object.keys returns an array of keys, so iteration order is preserved and keys are passed to the callback.
Concept Snapshot
Iterating over objects in JavaScript:
- Use for...in to loop keys: for (const key in obj) {}
- Access values with obj[key], not obj.key
- Order of keys is not guaranteed
- Alternative: Object.keys(obj).forEach(key => {})
- Use iteration to read or process each key-value pair
Full Transcript
This lesson shows how to loop over all keys in a JavaScript object using a for...in loop. We start with an object, get each key one by one, and access its value using bracket notation obj[key]. The loop runs until all keys are processed. We track the variable 'key' changing from 'a' to 'b' and print each key and value. Beginners often confuse obj[key] with obj.key; the first uses the variable key to access dynamic properties, while the second looks for a property literally named 'key'. The order of keys in for...in is not guaranteed. Alternatives like Object.keys(obj).forEach provide a way to iterate keys as an array. This visual trace helps understand each step and variable change during iteration.

Practice

(1/5)
1. Which of the following is the correct way to loop over all keys in a JavaScript object obj?
easy
A. obj.forEach(key => console.log(key));
B. for (let i = 0; i < obj.length; i++) { console.log(obj[i]); }
C. for (let key in obj) { console.log(key); }
D. for (let key of obj) { console.log(key); }

Solution

  1. Step 1: Understand looping over object keys

    The for...in loop is designed to iterate over all enumerable keys in an object.
  2. Step 2: Check each option's validity

    for (let key in obj) { console.log(key); } uses for...in correctly. for (let i = 0; i < obj.length; i++) { console.log(obj[i]); } tries to use a numeric index on an object, which doesn't work. for (let key of obj) { console.log(key); } uses for...of which works on iterable objects like arrays, not plain objects. obj.forEach(key => console.log(key)); tries to use forEach on an object, which is invalid.
  3. Final Answer:

    for (let key in obj) { console.log(key); } -> Option C
  4. Quick Check:

    Use for...in to loop keys [OK]
Hint: Use for...in to loop keys in objects [OK]
Common Mistakes:
  • Using for...of on plain objects
  • Trying to use numeric indexes on objects
  • Using forEach directly on objects
2. Which syntax correctly accesses the value of each key inside a for...in loop over object data?
easy
A. for (let key in data) { console.log(data[key]); }
B. for (let key in data) { console.log(key.value); }
C. for (let key in data) { console.log(data.key); }
D. for (let key in data) { console.log(data->key); }

Solution

  1. Step 1: Understand how to access object values by key

    Inside a for...in loop, key is a string representing the property name. To get the value, use bracket notation: data[key].
  2. Step 2: Evaluate each option

    for (let key in data) { console.log(data.key); } uses dot notation with a variable, which looks for a property literally named 'key'. for (let key in data) { console.log(data[key]); } correctly uses bracket notation. for (let key in data) { console.log(key.value); } tries to access key.value, but key is a string, not an object. for (let key in data) { console.log(data->key); } uses invalid syntax.
  3. Final Answer:

    for (let key in data) { console.log(data[key]); } -> Option A
  4. Quick Check:

    Access values with data[key] inside for...in [OK]
Hint: Use bracket notation data[key] to get values [OK]
Common Mistakes:
  • Using dot notation with variable key
  • Treating key as an object
  • Using invalid syntax like arrows
3. What will be the output of the following code?
const obj = {a: 1, b: 2, c: 3};
let result = [];
for (let key in obj) {
  result.push(key + obj[key]);
}
console.log(result);
medium
A. ['1', '2', '3']
B. ['1a', '2b', '3c']
C. ['a', 'b', 'c']
D. ['a1', 'b2', 'c3']

Solution

  1. Step 1: Understand the loop and concatenation

    The loop iterates over keys 'a', 'b', 'c'. For each key, it concatenates the key string with its value (number converted to string).
  2. Step 2: Trace the result array

    First iteration: 'a' + 1 = 'a1', second: 'b' + 2 = 'b2', third: 'c' + 3 = 'c3'. These are pushed into the array.
  3. Final Answer:

    ['a1', 'b2', 'c3'] -> Option D
  4. Quick Check:

    Keys + values concatenated = ['a1', 'b2', 'c3'] [OK]
Hint: Concatenate key + value inside for...in loop [OK]
Common Mistakes:
  • Confusing order of concatenation
  • Expecting numeric addition instead of string concat
  • Using keys or values alone
4. Identify the error in this code snippet:
const user = {name: 'Alice', age: 25};
for (let key of user) {
  console.log(key + ': ' + user[key]);
}
medium
A. Using for...of on a plain object causes a TypeError
B. Missing declaration of key variable
C. Incorrect string concatenation syntax
D. Accessing user[key] is invalid

Solution

  1. Step 1: Check the loop type and object

    for...of works on iterable objects like arrays or strings. Plain objects are not iterable, so this causes a TypeError.
  2. Step 2: Confirm other parts are correct

    The variable key is declared correctly. String concatenation and accessing user[key] are valid if the loop worked.
  3. Final Answer:

    Using for...of on a plain object causes a TypeError -> Option A
  4. Quick Check:

    for...of needs iterable, plain object is not [OK]
Hint: Use for...in or Object.keys() for objects, not for...of [OK]
Common Mistakes:
  • Using for...of on plain objects
  • Confusing variable declaration errors
  • Thinking user[key] is invalid
5. Given the object const scores = {alice: 10, bob: 0, carol: 5, dave: null};, which code snippet correctly creates a new object with only keys having truthy values?
hard
A. const filtered = {}; for (let key in scores) { if (scores.key) filtered.key = scores.key; }
B. const filtered = {}; for (let key in scores) { if (scores[key]) filtered[key] = scores[key]; }
C. const filtered = Object.keys(scores).filter(k => scores[k]).reduce((obj, k) => { obj[k] = scores[k]; }, {});
D. const filtered = Object.values(scores).filter(v => v);

Solution

  1. Step 1: Understand filtering truthy values in an object

    We want to keep keys where the value is truthy (not 0, null, undefined, false, '').
  2. Step 2: Analyze each option

    const filtered = {}; for (let key in scores) { if (scores[key]) filtered[key] = scores[key]; } uses a for...in loop and checks scores[key] truthiness correctly, adding to filtered. const filtered = {}; for (let key in scores) { if (scores.key) filtered.key = scores.key; } incorrectly uses dot notation with variable key. const filtered = Object.keys(scores).filter(k => scores[k]).reduce((obj, k) => { obj[k] = scores[k]; return obj; }, {}); tries to use Object.keys() with filter and reduce, but the code is missing a return statement in the arrow function (syntax error). const filtered = Object.values(scores).filter(v => v); filters values only, losing keys and returning an array, not an object.
  3. Final Answer:

    const filtered = {}; for (let key in scores) { if (scores[key]) filtered[key] = scores[key]; } -> Option B
  4. Quick Check:

    Use for...in with if (scores[key]) to filter [OK]
Hint: Use for...in and if (obj[key]) to filter truthy keys [OK]
Common Mistakes:
  • Using dot notation with variable keys
  • Confusing Object.values() with keys
  • Missing return in reduce arrow function
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard