Back to course

Iterating Arrays: The Modern 'for...of' Loop (ES6)

JavaScript: The Complete '0 to Hero' Beginner Course

57. Iterating Arrays with for...of

The for...of loop (introduced in ES6) is the simplest and most readable way to iterate directly over the values of an iterable object, like an Array or a String. It removes the need for managing the index counter.

Syntax

javascript for (const element of arrayName) { // Code to execute for each element }

Example

javascript const directions = ['North', 'East', 'South', 'West'];

for (const direction of directions) { // Note: 'direction' is the actual value, not the index. console.log(Moving: ${direction}); }

// Output: // Moving: North // Moving: East // ...

Getting the Index with for...of

If you need the index while using for...of, you must use the .entries() method.

javascript for (const [index, value] of directions.entries()) { console.log(Index ${index}: ${value}); }

Best Practice: Use for...of for clean, read-only iteration when the index is not critical.