JavaScript forEach()
The JavaScript forEach()
method is used to execute a function on each element in an array. It is one of the simplest ways to loop through an array and process each element with a custom function. The forEach()
method is available in all browsers and can be used in both ES6 (ECMAScript 2015) and earlier versions of JavaScript.
Syntax
The syntax for forEach()
is as follows:
array.forEach(function(currentValue, index, array) {
// code to be executed
}, thisArg);
currentValue
- The value of the current element being processed in the arrayindex
(optional) - The index of the current element being processed in the arrayarray
(optional) - The arrayforEach()
was called uponthisArg
(optional) - Object to use asthis
when executing the callback function
Example
Let's look at an example of using forEach()
to loop through an array of numbers and print each element to the console.
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
The output will be:
1
2
3
4
5