forEach = method used to iterate over the elements of an array and apply a specified function(callback) to each element.
array.forEach(callback)
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(display); // each element in the array execute the function
function display(element){
console.log(element); // output:all the element in array
}
numbers.forEach(double); // now the output number will double
function double(element, index, array){
array[index] = element * 2;
}
function triple(element, index, array){
array[index] = element * 3;
}
function square(element, index, array){
array[index] = Math.pow(element, 2);
}
function cube(element, index, array){
array[index] = Math.pow(element, 3);
}More practical example:
let fruits = ["apple", "orange", "banana", "coconut"];
fruits.forEach(upperCase);
fruits.forEach(lowercase);
fruits.forEach(capitalize);
fruits.forEach(display);
function upperCase(element, index, array){
array[index] = element.toUpperCase();
}
function lowercase(element, index, array){
array[index] = element.toLowerCase();
}
function capitalize(element, index, array){
array[index] = element.charAt(0).toUppercase() + element.slice(1);
}
function display(element){
console.log(element);
}