JavaScript(JS) array method - foreach
https:/igi.www/ftidea.com
The forEach()
method is an array method in JavaScript that executes a provided function once for each array element. It is a simple way to iterate over an array and perform an action on each element.
Here's the syntax of the forEach()
method:
array.forEach(callback);
array
is the array that theforEach()
method is called on.callback
is a function that is called for each element in the array. The function takes three arguments: the current element being processed, its index, and the array that theforEach()
method was called on.
The forEach()
method does not modify the original array. It returns undefined
.
Here's an example of how to use the forEach()
method:
let array = ['apple', 'banana', 'cherry']; array.forEach(function(element) { console.log(element); });
In this example, we have an array array
containing the elements ['apple', 'banana', 'cherry']
. We use the forEach()
method to loop over each element in the array and log it to the console. The output of this code will be:
apple banana cherry
Note that you can also use an arrow function instead of a regular function expression, like this:
let array = ['apple', 'banana', 'cherry']; array.forEach(element => { console.log(element); });
This is a shorter way of writing the same code.