Iterating over arrays in Javascript - Time & Space Complexity
When we go through each item in an array one by one, we want to know how the time it takes grows as the array gets bigger.
We ask: How does the work change when the array has more elements?
Analyze the time complexity of the following code snippet.
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
This code adds up all the numbers in the array by visiting each element once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each element of the array and adding it to sum.
- How many times: Exactly once for each element in the array.
As the array gets bigger, the number of steps grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the array size doubles the work needed.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the array.
[X] Wrong: "The loop runs faster because it just adds numbers, so it's constant time."
[OK] Correct: Even simple steps add up when repeated many times; the total time depends on how many elements there are.
Understanding how looping through arrays scales helps you explain your code clearly and shows you know how programs behave with bigger data.
"What if we used two nested loops to compare every pair of elements? How would the time complexity change?"
Practice
arr using for...of?Solution
Step 1: Understand
Thefor...ofsyntaxfor...ofloop directly accesses each element in the array, not the index.Step 2: Identify the correct loop structure
for (const item of arr) { console.log(item); } usesfor (const item of arr), which correctly iterates over elements.Final Answer:
for (const item of arr) { console.log(item); } -> Option DQuick Check:
for...ofloops over elements = C [OK]
for...of to get elements directly [OK]- Confusing
for...inwithfor...of - Using index instead of element in
for...of - Trying to use
forEachsyntax insidefor...of
forEach to print each element of array nums?Solution
Step 1: Recall
forEachmethod syntaxforEachis called on the array with a function as argument:array.forEach(function(item) { ... }).Step 2: Match correct syntax
nums.forEach(function(item) { console.log(item); }); correctly usesnums.forEach(function(item) { console.log(item); });which is valid.Final Answer:
nums.forEach(function(item) { console.log(item); }); -> Option AQuick Check:
array.forEach(function)syntax = A [OK]
array.forEach(function) calls function on each item [OK]- Trying to call
forEachas a standalone function - Missing parentheses around function argument
- Using arrow syntax incorrectly without parentheses
const arr = [1, 2, 3];
let sum = 0;
for (const num of arr) {
sum += num;
}
console.log(sum);Solution
Step 1: Understand the loop and sum calculation
The loop goes through each number inarr: 1, 2, 3, adding each tosum.Step 2: Calculate the total sum
sum = 0 + 1 + 2 + 3 = 6.Final Answer:
6 -> Option AQuick Check:
Sum of [1,2,3] = 6 [OK]
- Concatenating numbers as strings instead of adding
- Not initializing sum to 0
- Using wrong loop variable
items:const items = ['a', 'b', 'c'];
for (let i = 0; i <= items.length; i++) {
console.log(items[i]);
}Solution
Step 1: Analyze the loop condition
The loop runs whilei <= items.length. Since array indices go from 0 toitems.length - 1, this causes an out-of-bounds access ati = items.length.Step 2: Correct the loop condition
Change condition toi < items.lengthto avoid accessing undefined element.Final Answer:
The loop condition should bei < items.lengthinstead ofi <= items.length-> Option CQuick Check:
Loop index must be less than length, not less or equal [OK]
i < array.length to avoid out-of-range errors [OK]- Using <= instead of < in loop condition
- Trying to declare loop variable with const
- Ignoring array length boundaries
data = [0, 1, false, 2, '', 3]. You want to create a new array containing only the truthy values by iterating over data. Which code correctly does this?Solution
Step 1: Understand truthy filtering
We want to keep only values that are truthy (not 0, false, '', null, undefined).Step 2: Check each option
const result = []; data.forEach(item => { if (item) result.push(item); }); usesforEachto push only truthy items, which is correct. const result = data.filter(item => item == true); uses== truewhich misses some truthy values like numbers. const result = []; for (let i = 0; i < data.length; i++) { result.push(data[i]); } copies all items without filtering. const result = data.map(item => item ? item : null); replaces falsy with null, not filtering.Final Answer:
const result = []; data.forEach(item => { if (item) result.push(item); }); -> Option BQuick Check:
UseforEachwith if (item) to filter truthy [OK]
forEach with if (item) to keep truthy values [OK]- Using == true instead of checking truthiness
- Copying all elements without filtering
- Using map instead of filter or manual push
Ready to prove it?
Pass the test and this pattern moves unknown
