JavaScript Array.forEach() Method Example

The forEach() method executes a provided function once for each array element.

Syntax

arr.forEach(function callback(currentValue [, index [, array]]) {
    //your iterator
}[, thisArg]);
  1. callback - Function to execute on each element, taking three arguments:
  • currentValue - The current element being processed in the array.
  • index (Optional) - The index of the current element being processed in the array.
  • array (Optional) - The array forEach() was called upon.
  1. thisArg (Optional) - Value to use as this when executing the callback.

Examples

Example 1: Simple Array.forEach() Example

    var progLangs = ['Java', 'C', 'C++', 'PHP', 'Python'];
    progLangs.forEach(element => {
        console.log(element);
    });
Output:
Java
C
C++
PHP
Python

Example 2: Converting a for loop to forEach

const items = ['item1', 'item2', 'item3'];
const copy = [];

// before
for (let i=0; i<items.length; i++) {
  copy.push(items[i]);
}

// after
items.forEach(function(item){
  copy.push(item);
});

Comments

Post a Comment