Iterating over objects in Javascript - Time & Space Complexity
When we loop through all the properties of an object, the time it takes depends on how many properties there are.
We want to know how the work grows as the object gets bigger.
Analyze the time complexity of the following code snippet.
const obj = {a: 1, b: 2, c: 3};
for (const key in obj) {
console.log(key, obj[key]);
}
This code goes through each property in the object and prints its key and value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
for...inloop that visits each property in the object. - How many times: Once for every property in the object.
As the number of properties grows, the loop runs more times, doing more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the number of properties. Double the properties, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of properties in the object.
[X] Wrong: "Looping over an object is always constant time because objects are fast."
[OK] Correct: The loop visits every property, so if the object has more properties, it takes more time.
Understanding how looping over objects scales helps you write efficient code and answer questions about performance clearly.
"What if we used Object.keys(obj).forEach() instead of for...in? How would the time complexity change?"
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
