for...of Loop in JavaScript

The for...of loop is a modern iteration construct introduced in ECMAScript 2015 (ES6) that simplifies the process of iterating over iterable objects such as arrays, strings, maps, sets, and more. In this section, we'll explore the basic syntax and usage of the for...of loop.

Basic Syntax of for...of Loop

The syntax of a for...of loop is straightforward: for (variable of iterable) { // code block }. Here, variable represents a variable that will be assigned each element’s value in the iterable object, and iterable is the object over which we’re iterating. The loop iterates over each element of the iterable, allowing easy access to its values.

Understanding Iteration with for...of Loop

The for...of loop iterates over the values of an iterable object, making it simpler and more concise than traditional loops like for or for...in. It automatically handles the iteration logic, allowing you to focus on processing each element within the loop’s code block.

Basic for...of Loop

Let’s illustrate the basic usage of a for...of loop with an example. We’ll iterate over the elements of an array and log each element:

				
					const fruits = ['apple', 'banana', 'orange'];

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

				
			
				
					
apple
banana
orange


				
			

In this example, the for...of loop iterates over each element of the fruits array. In each iteration, the fruit variable is assigned the value of the current element, which is then logged to the console.

Advanced Concepts

Now, let’s delve into some advanced concepts related to the for...of loop in JavaScript:

  • Iterating Over Strings: Using the for...of loop to iterate over the characters of a string.
  • Iterating Over Other Iterable Objects: Exploring how the for...of loop can be used with other iterable objects like maps and sets.
  • Using Destructuring: Employing array destructuring with the for...of loop to access both index and value simultaneously.

In this example, we’ll demonstrate how to use the for...of loop to iterate over the characters of a string:

				
					const message = 'Hello, world!';

for (let char of message) {
  console.log(char);
}

				
			
				
					
H
e
l
l
o
,
 
w
o
r
l
d
!


				
			

The for...of loop iterates over each character of the message string, allowing us to process each character individually within the loop’s code block.

The for...of loop is a versatile iteration construct in JavaScript that simplifies the process of iterating over iterable objects. It provides a concise and intuitive syntax for working with arrays, strings, and other iterable objects, enhancing code readability and maintainability. By mastering the for...of loop, developers can streamline their iteration tasks and write more expressive and efficient JavaScript code.

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India