JS For Of Loop

JS For Of Loop

JS For Of Loop

 

The “for…of” loop is a new feature added in ECMAScript 6 (ES6) that provides an easier way to iterate over arrays, strings, maps, sets, and other iterable objects.

Here’s the basic syntax for the “for…of” loop:

				
					for (let element of iterable) {
  // code block to be executed
}

				
			

In this loop, “element” is a variable that will take on the value of each element in the iterable object as it iterates through the loop. The “iterable” is any object that can be iterated over, such as an array or a string.

Here’s an example of using the “for…of” loop to iterate over an array:

				
					let myArray = [1, 2, 3, 4, 5];

for (let element of myArray) {
  console.log(element);
} 

				
			

This code will output the numbers 1, 2, 3, 4, and 5 to the console, one at a time, because the “for…of” loop iterates through each element in the array and assigns it to the “element” variable.

One advantage of the “for…of” loop is that it automatically handles iterating over the elements of an iterable object without requiring you to manually track the index, as you would with a traditional “for” loop.

Join To Get Our Newsletter
Spread the love