JavaScript

coding learning websites codepractice

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


📘 JavaScript for...of Loop – The Modern Way to Iterate

The for...of loop lets you iterate over iterable objects like:

  • Arrays

  • Strings

  • Sets

  • Maps

  • NodeLists (in browsers)

It gives direct access to the value in each iteration, rather than the index or key.


🔹 Syntax

for (let variable of iterable) {
  // code block to be executed
}
  • variable — A new variable representing the current value in the loop.

  • iterable — A data structure that you want to loop over (like an array or string).


🔹 Example 1 – Iterating Over an Array

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

for (let color of colors) {
  console.log(color);
}
// Output: red green blue

🔹 Example 2 – Iterating Over a String

let word = "Hello";

for (let char of word) {
  console.log(char);
}
// Output: H e l l o

🔹 Example 3 – Iterating Over a Set

let numbers = new Set([1, 2, 3]);

for (let num of numbers) {
  console.log(num);
}

🔹 Example 4 – Iterating Over Map Values

let userMap = new Map([
  ["name", "Alice"],
  ["age", 30],
]);

for (let [key, value] of userMap) {
  console.log(`${key}: ${value}`);
}

🔹 Key Difference: for...of vs for...in

Feature for...in for...of
Loops over Object keys Iterable values
Use with Objects Arrays, strings, sets, maps
Returns Key/index Actual value
Suitable for Objects Arrays and other iterables

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?


JavaScript

online coding class codepractice

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