JavaScript’s Array#forEach()
function is one of several ways to iterate through a JavaScript array. It is generally considered one of the “functional programming” methods along with filter()
, map()
, and reduce()
.
The forEach()
method takes a parameter callback
, which is a function that JavaScript will execute on every element in the array.
// Prints "a", "b", "c"
['a', 'b', 'c'].forEach(v => {
console.log(v);
});
JavaScript calls your callback
with 3 parameters: currentValue
, index
, and array
. The index
parameter is how you get the current array index with forEach()
.
// Prints "0: a, 1: b, 2: c"
['a', 'b', 'c'].forEach(function callback(value, index) {
console.log(`${index}: ${value}`);
});
#javascript #programming #developer #web-development