JavaScript Code


JavaScript Array forEach()


forEach() – Action for each Element of Array

array.forEach(element => {
    //code
});

//or

array.forEach(action);
  • array is an array of elements
  • forEach is the array method name
  • action is a function that can take element as argument

forEach() method executes the given block of code, or action, for each element of the array

Examples

1. execute a function printElementLength() for each element of the array fruits

function printElementLength(element) {
    console.log(element + ' - ' + element.length);
}

let fruits = ['apple', 'banana', 'cherry', 'fig'];
fruits.forEach(printElementLength);

2. execute a block of code for each element of the array fruits

let fruits = ['apple', 'banana', 'cherry', 'fig'];
fruits.forEach(element => {
    console.log(element + ' - ' + element.length);
});

Copyright @2022