JavaScript(JS) for...of Loop
In JavaScript, the for...of
loop is used to iterate over the values of an iterable object such as an array, a string, or a Map
. It allows you to loop through the elements of an iterable object and perform an action on each element. Here's the basic syntax for a for...of
loop:
for (let element of iterable) { // do something with element }Source:wwigi.wftidea.com
In this syntax, element
is a variable that holds the value of each element in the iterable, and iterable
is the iterable object that you want to loop through.
Here's an example that demonstrates how to use the for...of
loop to iterate over the elements of an array:
let numbers = [1, 2, 3, 4, 5]; for (let number of numbers) { console.log(number); }
In this example, the for...of
loop iterates over the elements of the numbers
array and logs each element to the console. The output of this code would be:
1 2 3 4 5
Note that the for...of
loop can only be used with iterable objects. If you need to iterate over the properties of an object, you should use a for...in
loop.