for…of Loop in JavaScript
In JavaScript, the for...of loop is a control flow statement introduced in ECMAScript 6 (ES6). It provides an easy and concise way to iterate over iterable objects, including arrays, strings, sets, maps, and more. The for...of loop simplifies the process of accessing and iterating through the elements of such collections. It is used to iterate over the elements of an iterable object, like array, string, etc.
The syntax of for…of loop in JavaScript is-
for(variable of iterable){
//code
}
Here's how the for...of loop in JavaScript works:
- The variable represents a new variable that is assigned the value of each element in the iterable object on each iteration of the loop.
- The iterable is any object that can be iterated over. It can be an array, a string, a set, a map, or any other object that implements the iterable protocol.
- The code block inside the loop is executed for each element in the iterable, with the variable holding the value of the current element.
Example 1:
const even= [2,4,6];
for (let num of even){
console.log(num);
}
2
4
6
Inference: In this code, the loop iterates over each element of the the given values and prints the output as the result.
Example 2:
const fruits = ['apple', 'banana', 'orange'];
for (let fruit of fruits) {
console.log(fruit);
}
apple
banana
orange
Inference : As you can see, the loop iterates over each element of the array, and we can directly access the value of each element using the fruit variable.
Conclusion
To summarize, the for...of loop in JavaScript simplifies the iteration process over iterable objects. It provides a concise syntax for accessing and working with elements in arrays, strings, sets, maps, and other iterable objects. By understanding its syntax and usage, you can leverage the power of the for...of loop to iterate through collections in your JavaScript programs.