for...of vs. forEach in Javascript
In JavaScript, there are several ways to iterate through the elements of an array, one of which is the for...of loop, and another is the forEach() method.
The for...of loop
The for...of loop is a way to iterate over the values of an array or other iterable objects, like strings, maps, sets, etc.
Syntax
In JavaScript, the syntax for a for...of loop is as follows:
for (variable of iterable) {
// code to be executed for each value of the iterable
}
Here, the variable will take on the value of each element in the iterable object as the loop iterates. Whereas,
iterable is an object that can be iterated over, such as an array, a string, a map, or a met.
Example
Here’s an example of using a for...of loop to iterate through the elements of an array.
let alphabets = ['a', 'b', 'c', 'd'];for (let alphabet of alphabets){console.log(alphabet);}
Explanation
- Line 1: We initialize an array using a
letkeyword. - Lines 3–6: The
forkeyword begins the loop. This loop iterates over all the elements in thealphabetscontainer. It assigns the element to the variablealphabetfor each element and prints it to the console.
The forEach() method
The forEach() method is a way to iterate through the elements of an array and apply a function to each element. Here’s an example of using the forEach() method to iterate through the elements of an array:
Syntax
The syntax for using the forEach() method is as follows:
array.forEach(function(currentValue, index, array) {
// code to be executed for each element of the array
});
Here, array is the array that you want to iterate over, and function is the function that will be applied to each element. The function takes 3 arguments:
-
currentValueis the current element being processed in the array. -
index(optional) is the index of the current element being processed in the array. -
array(optional) is the array being processed.
Example
Here’s an example of using the forEach() method to iterate through the elements of an array and print each element:
let alphabets = ['a', 'b','c','d'];alphabets.forEach(function(alphabet){console.log(alphabet);});
Explanation
- Line 1: We initialize an array using the
letkeyword. - Lines 3–6: The function passed to
forEach()takes one parameter, “alphabet”, representing each element in the array as the function iterates through it. Inside the function, there is one line of code,console.log(alphabet);. This line of code will print the currentalphabetelement of the array to the console.
Note: The
forEach()method can only be used on an array and if you try to use it on any other object it will throw an error.
Free Resources