JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Loop For Of


The for...of loop in JavaScript is a modern and powerful way to iterate over iterable objects, such as arrays, strings, maps, sets, and other objects that implement the iterable protocol. Unlike the for...in loop, which iterates over property names, for...of iterates over the values of an iterable, making it ideal for array processing and sequential access to data.

This tutorial provides a detailed explanation of the for...of loop, practical examples, best practices, common mistakes, and real-world applications.

Why the For Of Loop Is Important

The for...of loop is important because it:

  • Simplifies iteration over iterable objects like arrays, strings, maps, and sets.

  • Provides a clean, readable syntax for processing values.

  • Eliminates the need for manual index management in arrays.

  • Works with any object that implements the iterable protocol.

  • Supports destructuring, making it convenient for complex data structures.

It is especially useful in modern JavaScript development for working with collections and performing operations without worrying about property names or numeric indices.

Syntax

The syntax of the for...of loop is:

for (const variable of iterable) {
  // Code to execute in each iteration
}
  • variable – Represents the value of the current iteration.

  • iterable – An object that implements the iterable protocol (e.g., array, string, map, set).

Unlike for...in, for...of iterates over values, not keys.

Example 1: Iterating Over an Array

let names = ["Aarushi", "Priya", "Ananya", "Isha", "Meera"];

for (let name of names) {
  console.log(name);
}

Output:

Aarushi
Priya
Ananya
Isha
Meera

Here, name directly represents each value in the array, simplifying array processing.

Example 2: Iterating Over a String

let name = "Ananya";

for (let letter of name) {
  console.log(letter);
}

Output:

A
n
a
n
y
a

The for...of loop works on strings, allowing you to access each character sequentially.

Example 3: Iterating Over a Set

let students = new Set(["Aarushi", "Isha", "Meera"]);

for (let student of students) {
  console.log(student.toUpperCase());
}

Output:

AARUSHI
ISHA
MEERA

Sets are iterable, and for...of makes processing each element straightforward.

Example 4: Iterating Over a Map

let studentGrades = new Map();
studentGrades.set("Priya", "A");
studentGrades.set("Ananya", "B");
studentGrades.set("Isha", "A");

for (let [name, grade] of studentGrades) {
  console.log(`${name}: ${grade}`);
}

Output:

Priya: A
Ananya: B
Isha: A

Destructuring allows easy access to both the key and value in each iteration.

Nested For Of Loops

for...of loops can be nested to handle multi-dimensional arrays or collections:

let classroom = [
  ["Aarushi", "Priya"],
  ["Ananya", "Isha"],
  ["Meera", "Saanvi"]
];

for (let row of classroom) {
  for (let student of row) {
    console.log(student);
  }
}

Output:

Aarushi
Priya
Ananya
Isha
Meera
Saanvi

Nested loops are useful for working with grids, tables, or complex data structures.

Example 5: Counting Characters in Names

let names = ["Aarushi", "Priya", "Ananya"];

for (let name of names) {
  console.log(`${name} has ${name.length} letters`);
}

Example 6: Filtering Names Starting With 'A'

let names = ["Aarushi", "Priya", "Ananya", "Isha"];

for (let name of names) {
  if (name.startsWith("A")) {
    console.log(name + " starts with A");
  }
}

Example 7: Creating a Greetings List

let names = ["Meera", "Saanvi", "Isha"];

for (let name of names) {
  console.log(`Hello, ${name}!`);
}

Output:

Hello, Meera!
Hello, Saanvi!
Hello, Isha!

Example 8: Iterating Over Map of Student Marks

let studentMarks = new Map([
  ["Aarushi", 85],
  ["Priya", 90],
  ["Ananya", 78]
]);

for (let [student, marks] of studentMarks) {
  console.log(`${student} scored ${marks} marks`);
}

Example 9: Iterating Over Object Values

Objects are not directly iterable, but you can use Object.values() with for...of:

let student = {
  name: "Isha",
  age: 15,
  grade: "A"
};

for (let value of Object.values(student)) {
  console.log(value);
}

Output:

Isha
15
A

Common Mistakes

  • Trying to use for...of directly on plain objects.

  • Confusing for...of with for...in, which iterates over keys instead of values.

  • Using var instead of let or const for loop variables in block scope.

  • Modifying the iterable while iterating, which can produce unexpected behavior.

Best Practices

  • Use for...of for arrays, strings, sets, and maps for clean value iteration.

  • Prefer const for loop variables if they are not reassigned.

  • Combine with destructuring for easier access to key-value pairs.

  • Avoid using for...of for objects; use for...in or Object.keys()/values() instead.

  • Keep loops readable and avoid heavy computations inside the loop.

Real-World Applications

  • Processing API responses returned as arrays or sets.

  • Iterating through user input for validation.

  • Manipulating strings character by character.

  • Iterating over map entries for key-value operations.

  • Generating dynamic content in web applications, such as lists, tables, or menus.

Summary of JS Loop For Of

The for...of loop in JavaScript provides a clean and efficient way to iterate over iterable objects like arrays, strings, sets, and maps. It allows direct access to values, supports destructuring, and simplifies iteration compared to traditional for loops or for...in loops. Following best practices and avoiding common mistakes ensures concise, readable, and maintainable code for a wide range of real-world applications.


Practice Questions

Q1. How do you loop through all elements of an array using for...of?

Q2. What is the output of a for...of loop on the string "hello"?

Q3. How can you use for...of to iterate over a Set object in JavaScript?

Q4. How do you use destructuring with for...of when looping through a Map?

Q5. What happens when you use for...of on an object that is not iterable?

Q6. How is for...of different from for...in in terms of return value?

Q7. Can you use for...of to loop through the characters of a string?

Q8. How do you skip an iteration inside a for...of loop?

Q9. Write a for...of loop that prints the squares of numbers in an array.

Q10. How do you iterate through values of a NodeList using for...of in the browser?


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top