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.
for...of
loopThe for...of loop
is a way to iterate over the values of an array or other iterable objects, like strings, maps, sets, etc.
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.
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);}
let
keyword.for
keyword begins the loop. This loop iterates over all the elements in the alphabets
container. It assigns the element to the variable alphabet
for each element and prints it to the console.forEach()
methodThe 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:
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:
currentValue
is 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.
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);});
let
keyword.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 current alphabet
element 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