Bird
Raised Fist0
Javascriptprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - Iterating over arrays
Start with array
↓
Set index i = 0
↓
Check: i < array.length?
No→Exit loop
Yes↓
Access array[i
↓
Execute loop body
↓
Increment i by 1
↩Back to Check
We start with an array and an index at 0. We check if the index is less than the array length. If yes, we access the element at that index, run the loop body, then increase the index by 1. Repeat until the index reaches the array length.
Execution Sample
Javascript
const arr = [10, 20, 30];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
This code prints each element of the array one by one.
Execution Table
IterationiCondition (i < arr.length)ActionOutput
100 < 3 → truePrint arr[0] = 1010
211 < 3 → truePrint arr[1] = 2020
322 < 3 → truePrint arr[2] = 3030
433 < 3 → falseExit loop
💡 i reaches 3, condition 3 < 3 is false, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
iundefined0123
arr[i]N/A102030N/A
Key Moments - 3 Insights
Why does the loop stop when i equals arr.length?
Because the condition i < arr.length becomes false at that point, as shown in execution_table row 4, so the loop exits.
Why do we start i at 0 instead of 1?
Array indexes start at 0 in JavaScript, so to access the first element, i must be 0. This is shown in execution_table row 1 where i=0 accesses arr[0].
What happens if we use i <= arr.length instead of i < arr.length?
The loop would try to access arr[arr.length], which is undefined and may cause unexpected behavior. The condition must be strictly less than arr.length.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i during the third iteration?
A2
B3
C1
D0
💡 Hint
Check the 'i' column in execution_table row 3.
At which iteration does the loop condition become false?
AIteration 2
BIteration 4
CIteration 3
DIteration 1
💡 Hint
Look at the 'Condition' column in execution_table row 4.
If the array length was 4 instead of 3, how many times would the loop run?
A5 times
B3 times
C4 times
D2 times
💡 Hint
The loop runs while i < arr.length, so it runs once per index from 0 to length-1.
Concept Snapshot
for loop syntax to iterate arrays:
for (let i = 0; i < array.length; i++) {
  // use array[i]
}
Starts i at 0, runs while i < length, increments i by 1 each time.
Access elements by array[i].
Full Transcript
This visual trace shows how a for loop iterates over an array in JavaScript. We start with index i at 0 and check if i is less than the array length. If true, we access the element at array[i] and run the loop body, then increase i by 1. This repeats until i equals the array length, when the loop stops. The execution table shows each iteration's index, condition check, action, and output. The variable tracker shows how i and array[i] change step by step. Common confusions include why the loop stops at i equals length, why i starts at 0, and what happens if the condition is changed incorrectly. The quiz tests understanding of these steps.

Practice

(1/5)
1. Which of the following is the correct way to iterate over all elements in an array arr using for...of?
easy
A. arr.forEach(item => console.log(item));
B. for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
C. for (const i in arr) { console.log(arr[i]); }
D. for (const item of arr) { console.log(item); }

Solution

  1. Step 1: Understand for...of syntax

    The for...of loop directly accesses each element in the array, not the index.
  2. Step 2: Identify the correct loop structure

    for (const item of arr) { console.log(item); } uses for (const item of arr), which correctly iterates over elements.
  3. Final Answer:

    for (const item of arr) { console.log(item); } -> Option D
  4. Quick Check:

    for...of loops over elements = C [OK]
Hint: Use for...of to get elements directly [OK]
Common Mistakes:
  • Confusing for...in with for...of
  • Using index instead of element in for...of
  • Trying to use forEach syntax inside for...of
2. Which of the following is the correct syntax to use forEach to print each element of array nums?
easy
A. nums.forEach(function(item) { console.log(item); });
B. forEach(nums, item => console.log(item));
C. nums.forEach => console.log(item);
D. nums.forEach(item) { console.log(item); }

Solution

  1. Step 1: Recall forEach method syntax

    forEach is called on the array with a function as argument: array.forEach(function(item) { ... }).
  2. Step 2: Match correct syntax

    nums.forEach(function(item) { console.log(item); }); correctly uses nums.forEach(function(item) { console.log(item); }); which is valid.
  3. Final Answer:

    nums.forEach(function(item) { console.log(item); }); -> Option A
  4. Quick Check:

    array.forEach(function) syntax = A [OK]
Hint: Remember array.forEach(function) calls function on each item [OK]
Common Mistakes:
  • Trying to call forEach as a standalone function
  • Missing parentheses around function argument
  • Using arrow syntax incorrectly without parentheses
3. What will be the output of the following code?
const arr = [1, 2, 3];
let sum = 0;
for (const num of arr) {
  sum += num;
}
console.log(sum);
medium
A. 6
B. 123
C. 0
D. undefined

Solution

  1. Step 1: Understand the loop and sum calculation

    The loop goes through each number in arr: 1, 2, 3, adding each to sum.
  2. Step 2: Calculate the total sum

    sum = 0 + 1 + 2 + 3 = 6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Sum of [1,2,3] = 6 [OK]
Hint: Add each element inside the loop to get total sum [OK]
Common Mistakes:
  • Concatenating numbers as strings instead of adding
  • Not initializing sum to 0
  • Using wrong loop variable
4. Find the error in this code snippet that tries to print each element of items:
const items = ['a', 'b', 'c'];
for (let i = 0; i <= items.length; i++) {
  console.log(items[i]);
}
medium
A. The console.log statement is missing parentheses
B. The variable i should be declared with const
C. The loop condition should be i < items.length instead of i <= items.length
D. The array items is not defined

Solution

  1. Step 1: Analyze the loop condition

    The loop runs while i <= items.length. Since array indices go from 0 to items.length - 1, this causes an out-of-bounds access at i = items.length.
  2. Step 2: Correct the loop condition

    Change condition to i < items.length to avoid accessing undefined element.
  3. Final Answer:

    The loop condition should be i < items.length instead of i <= items.length -> Option C
  4. Quick Check:

    Loop index must be less than length, not less or equal [OK]
Hint: Use i < array.length to avoid out-of-range errors [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Trying to declare loop variable with const
  • Ignoring array length boundaries
5. You have an array 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?
hard
A. const result = data.filter(item => item == true);
B. const result = []; data.forEach(item => { if (item) result.push(item); });
C. const result = []; for (let i = 0; i < data.length; i++) { result.push(data[i]); }
D. const result = data.map(item => item ? item : null);

Solution

  1. Step 1: Understand truthy filtering

    We want to keep only values that are truthy (not 0, false, '', null, undefined).
  2. Step 2: Check each option

    const result = []; data.forEach(item => { if (item) result.push(item); }); uses forEach to push only truthy items, which is correct. const result = data.filter(item => item == true); uses == true which 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.
  3. Final Answer:

    const result = []; data.forEach(item => { if (item) result.push(item); }); -> Option B
  4. Quick Check:

    Use forEach with if (item) to filter truthy [OK]
Hint: Use forEach with if (item) to keep truthy values [OK]
Common Mistakes:
  • Using == true instead of checking truthiness
  • Copying all elements without filtering
  • Using map instead of filter or manual push
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