JavaScript Array.forEach() | Calls Function For Each Element of an Array

JavaScript Array.forEach() | Calls Function For Each Element of an Array

In this tutorial, you will learn all about JavaScript array forEach() Method & how to use this method.

JavaScript array.forEach()

Usually, when you have a javascript array.

See the following:

let nums = [1, 2, 3, 4]; 

And want to call a function on each element of an array, at that time, you use javascript for loop statement.

For example, see the following code:

let nums = [1, 2, 3, 4]; 
for (let i = 0; i < nums.length; i++) {
    console.log(nums[i]);
}

Output:

1
2
3
4

javascript array provides a method which is forEach(), this method permits the call of a function on each element of an array in an easy way.

See the following example:

let nums = [1, 2, 3, 4]; 
nums.forEach(function (e) {
    console.log(e);
});

Output:

1
2
3
4

The following represents the syntax of the forEach() method:

array.forEach(function(currentValue, index, arr), thisValue)
  • currentValue:- Value of the current element in array
  • index:- index of the current element in array
  • arr:- array object the current element belongs to.

This is not chainable like other iterative methods like: filter(), map(), some(), every(), and sort(), returns undefined.

Example 1: forEach() with numeric array

 var num = [18, 12, 10, 15];
 num.forEach(function(item) {
    document.writeln(item);
 });

Output

 // return 

18 12 10 15

How it works:

  • Define an array of with numeric elements.
  • After that, call the forEach() method on the num array. And print each element from array using document.writeln.

Example 2: forEach() with push()

var num = [2, 5, 10, 12];
var newArr = [];

num.forEach(function(num){
  newArr.push(num*num);
});

document.writeln(newArr);

Output

Output
// return

4,25,100,144

Note : The JavaScript Example to calculate square root of given numbers in array.

How it works:

  • First define an array with numbers.
  • Then, declare a new array newArr.
  • After that, call the forEach() method on the num array. Inside the callback function, calculate square root of the element and push value into newArr array using push() method.
  • Finally, print the new array with square root values.

Conclusion

In this tutorial, you have learned how to use the JavaScript Array forEach() method and to call a callback on each element of a javascript array.

Leave a Reply

Your email address will not be published. Required fields are marked *