Traverse arrays with for...of
Quick answer
A for...of loop consumes values from an iterable such as an array. An indexed for loop gives explicit control over positions and bounds.
How it works
Use for (const value of items). Each iteration binds the next value. On an ordinary array a missing position is read as undefined; for...in instead enumerates enumerable string property names and is not a value loop.
let sum = 0;for (const n of [3, 5, 2]) sum += n;console.log(sum);Expected output in Node.js:
10The loop receives the values, not their indices.
const a = [4, 7, 9];for (let i = 0; i < a.length; i++) { console.log(i, a[i]); }Expected output in Node.js:
0 41 72 9The index is available for position-dependent logic.
Common mistakes
Avoid changing array length while traversing unless you explicitly reason about the changed bounds. Use an indexed loop when the index matters.
Practice
Count values greater than 5 in a numeric array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Traverse arrays with for...of — Knowledge Check
Apply the taught concept and reason about the result.
In for (const n of [5,8]), what are the successive n values?
What does for...in enumerate?
What is the usual upper-bound test for indexing a dense array a?
Which loop is convenient when the numeric index is required?
What does an ordinary array iterator read for a hole with no inherited indexed value?