What if you could instantly check every detail in a messy box without lifting a finger?
Why Iterating over objects in Javascript? - Purpose & Use Cases
Imagine you have a box full of different toys, and you want to check each toy one by one to see which ones are cars. Doing this by picking each toy manually without any system can be tiring and confusing.
Manually checking each toy means you might forget some, mix up the order, or spend too much time. Similarly, manually accessing each property in an object one by one is slow and easy to mess up, especially if the object has many properties.
Iterating over objects lets you automatically go through every property in the object, like having a magic list that shows you each toy one after another without missing any. This saves time and avoids mistakes.
console.log(obj.name); console.log(obj.age); console.log(obj.city);
for (const key in obj) { if (obj.hasOwnProperty(key)) { console.log(key, obj[key]); } }
It makes handling all parts of an object easy and fast, opening doors to smarter and cleaner code.
Think of a contact list app that stores names and phone numbers. Iterating over the contacts lets the app quickly show all names and numbers without writing code for each one separately.
Manually accessing object properties is slow and error-prone.
Iterating over objects automates checking each property.
This leads to cleaner, faster, and more reliable code.
Practice
obj?Solution
Step 1: Understand looping over object keys
Thefor...inloop is designed to iterate over all enumerable keys in an object.Step 2: Check each option's validity
for (let key in obj) { console.log(key); } usesfor...incorrectly. 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); } usesfor...ofwhich works on iterable objects like arrays, not plain objects. obj.forEach(key => console.log(key)); tries to useforEachon an object, which is invalid.Final Answer:
for (let key in obj) { console.log(key); } -> Option CQuick Check:
Use for...in to loop keys [OK]
- Using for...of on plain objects
- Trying to use numeric indexes on objects
- Using forEach directly on objects
for...in loop over object data?Solution
Step 1: Understand how to access object values by key
Inside afor...inloop,keyis a string representing the property name. To get the value, use bracket notation:data[key].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 accesskey.value, butkeyis a string, not an object. for (let key in data) { console.log(data->key); } uses invalid syntax.Final Answer:
for (let key in data) { console.log(data[key]); } -> Option AQuick Check:
Access values with data[key] inside for...in [OK]
- Using dot notation with variable key
- Treating key as an object
- Using invalid syntax like arrows
const obj = {a: 1, b: 2, c: 3};
let result = [];
for (let key in obj) {
result.push(key + obj[key]);
}
console.log(result);Solution
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).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.Final Answer:
['a1', 'b2', 'c3'] -> Option DQuick Check:
Keys + values concatenated = ['a1', 'b2', 'c3'] [OK]
- Confusing order of concatenation
- Expecting numeric addition instead of string concat
- Using keys or values alone
const user = {name: 'Alice', age: 25};
for (let key of user) {
console.log(key + ': ' + user[key]);
}Solution
Step 1: Check the loop type and object
for...ofworks on iterable objects like arrays or strings. Plain objects are not iterable, so this causes a TypeError.Step 2: Confirm other parts are correct
The variablekeyis declared correctly. String concatenation and accessinguser[key]are valid if the loop worked.Final Answer:
Using for...of on a plain object causes a TypeError -> Option AQuick Check:
for...of needs iterable, plain object is not [OK]
- Using for...of on plain objects
- Confusing variable declaration errors
- Thinking user[key] is invalid
const scores = {alice: 10, bob: 0, carol: 5, dave: null};, which code snippet correctly creates a new object with only keys having truthy values?Solution
Step 1: Understand filtering truthy values in an object
We want to keep keys where the value is truthy (not 0, null, undefined, false, '').Step 2: Analyze each option
const filtered = {}; for (let key in scores) { if (scores[key]) filtered[key] = scores[key]; } uses afor...inloop and checksscores[key]truthiness correctly, adding tofiltered. 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 useObject.keys()withfilterandreduce, 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.Final Answer:
const filtered = {}; for (let key in scores) { if (scores[key]) filtered[key] = scores[key]; } -> Option BQuick Check:
Use for...in with if (scores[key]) to filter [OK]
- Using dot notation with variable keys
- Confusing Object.values() with keys
- Missing return in reduce arrow function
Ready to prove it?
Pass the test and this pattern moves unknown
