JavaScript - for...of loop in JavaScript

Alright, let's deeply explain the for...of loop in JavaScript with arrays and strings, including syntax, examples, and comparisons with other loops.


1. What is for...of in JavaScript?

The for...of loop is used to iterate over iterable objects like:

  • Arrays

  • Strings

  • Maps

  • Sets

  • NodeLists

  • And other iterable objects

It directly gives you the values of the iterable, not the indexes.


2. Syntax

for (const element of iterable) {
    // Code to execute
}
  • const or let: Variable to store the current element.

  • element: Each value in the iterable.

  • iterable: An object you want to loop through (e.g., array, string).


3. for...of with Arrays

Example 1: Simple Array Iteration

const fruits = ["apple", "banana", "mango"];

for (const fruit of fruits) {
    console.log(fruit);
}

Output:

apple
banana
mango

Here, fruit directly gives values, not indexes.


Example 2: Using for...of with break and continue

const numbers = [10, 20, 30, 40, 50];

for (const num of numbers) {
    if (num === 30) continue;  // skip 30
    if (num === 40) break;     // stop at 40
    console.log(num);
}

Output:

10
20
50
  • continue → skips the current iteration.

  • break → exits the loop.


Example 3: for...of with entries() to Get Index + Value

By default, for...of does not give the index.
But we can use array.entries() to get both index and value:

const colors = ["red", "green", "blue"];

for (const [index, color] of colors.entries()) {
    console.log(`${index}: ${color}`);
}

Output:

0: red
1: green
2: blue

4. for...of with Strings

Strings are iterable, so we can use for...of to loop through each character.

Example 1: Loop Through Characters

const word = "JavaScript";

for (const char of word) {
    console.log(char);
}

Output:

J
a
v
a
S
c
r
i
p
t

Example 2: Count Vowels in a String

const str = "Hello World";
let vowels = 0;

for (const char of str.toLowerCase()) {
    if ("aeiou".includes(char)) {
        vowels++;
    }
}

console.log(`Total vowels: ${vowels}`);

Output:

Total vowels: 3

5. Difference Between for...of and for...in

Feature for...of (Values) for...in (Keys/Indexes)
Iterates over Values of an iterable Indexes / property names
Works with arrays ✅ Yes ✅ Yes
Works with strings ✅ Yes ❌ Not recommended
Use case When you need values When you need indexes

Example:

const arr = ["a", "b", "c"];

// for...in gives INDEXES
for (const i in arr) {
    console.log(i); 
}
// Output: 0, 1, 2

// for...of gives VALUES
for (const val of arr) {
    console.log(val);
}
// Output: a, b, c

6. When to Use for...of

  • Use for...of when you only need values.

  • Use for...in when you need indexes or object keys.

  • Use forEach() when you want a cleaner functional style.