array.forEach()
iterates through each value in the array, passing it to a callback function one at a time. This allows you to manipulate the values within the callback.
For demonstration, consider the following code snippet:
let array = [1,2,3,4];
let product = 1;
array.forEach(x => {
console.log(x);
// update the product variable
product *= x;
});
console.log(product);
If you attempt to execute array.forEach(x, ...)
in the console, you will see undefined
because array.forEach()
does not return a value.
Other array methods like .map()
, .filter()
, .reduce()
, etc., do have return values. You can choose the appropriate method based on the specific operation you want to perform on the array.
For instance, the previous example could be re-written using .reduce()
:
let array = [1,2,3,4];
let product = array.reduce((total, x) => {
console.log(x);
return total * x;
}, 1);
console.log(product);
Here is an example of using .map()
to create a new array with each value squared:
let array = [1,2,3,4];
let product = array.map(x => {
return x ** 2;
}, 1);
console.log(product);