JavaScript Array.forEach() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript array.forEach():
  2. Example Code: Use the array.forEach() Method to Edit the Text of Each Element of a Given Array
  3. Example Code: Use the array.forEach() Method to Check Whether Any Element in an Array Is Less Than 5
  4. Example Code: Use the array.forEach() Method With the this Parameter to Get the Output
JavaScript Array.forEach() Method

In JavaScript, the array.forEach() method iterates over the elements of any iterable object. Users can add different elements and texts to the given array and perform some action on every element of the array using the array.forEach() method.

Syntax of JavaScript array.forEach():

refarray.forEach(function(currentValue));
refarr.forEach(function(currentValue,index,arr){ /* ... */}, this);

Parameters

callback function() The function that will run on each element in the given array.
currentValue The current element’s value is required to execute the function on each element.
index The current element’s index is optional.
arr The current array is optional.
this The this parameter is optional and is used in the callback function.

Return

This method returns an undefined output for each element in the array based on the condition mentioned in the function.

Example Code: Use the array.forEach() Method to Edit the Text of Each Element of a Given Array

In JavaScript, we can use the array.forEach() method to add text or edit the value of each element in a given array.

In this example, we created an array and used the array.forEach() method to run a function on each element. We have used the words, index, and arr as parameters.

In the function, we used the .toUpperCase() method to change the first letter of each element to uppercase. We also gave a condition that if the length of the array[1] is equal to array[0], it will give the output.

let array = ["java","script"];
let output = "";
var res = [];
array.forEach(capitalize);
function capitalize(words,index,arr){if (arr[1].length = arr[0].length)
    output += words[0].toUpperCase() + words.substring(1);
    res.push(output);
}
console.log(res);

Output:

[ 'Java', 'JavaScript' ]

Example Code: Use the array.forEach() Method to Check Whether Any Element in an Array Is Less Than 5

The array.forEach() method can determine each number’s value within an array. In the example, we created an array of numbers and used the array.forEach() method to find numbers that are less than 5.

The following function iterated over each element of the given array.

let num = [2, 4, 25, 48, 120];
num.forEach(function(number){
    if (number < 5) {
        console.log(number + " is less than 5");
    }
})

Output:

2 is less than 5
4 is less than 5

Example Code: Use the array.forEach() Method With the this Parameter to Get the Output

In JavaScript, the this keyword can refer to the values inside the scope where it is used. In the example, we will pass the this keyword as an argument of forEach and use it inside the callback function whenever the callback function is invoked.

We have a method inside the Array class to get the average of all the elements of the array. We will iterate through every array element, access the average variable inside the callback function using the this keyword, and store the value.

We have created the array object and invoked the aver method on that array to get the average of all elements.

class Array {
    constructor() {
       this.average = 0;
    }
    aver(array) {
        array.forEach(function average(math) {
        this.average += math/3;
        },this);
    }
}
const array = new Array();
array.aver([1.2,4.6,6.2]);
console.log(array.average);

Output:

4

The array.forEach() method executes a function for each element in a given array. Users can modify or change the value of each element using the array.forEach() method.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Array