JavaScript forEach Method By Example

JavaScript forEach Method By Example

Today we are going to show how to use JavaScript forEach Array Method & how it works. We will give an easy example of forEach array function.

The JavaScript Array Method – forEach () imposes a specific function for each item in a particular array individually. Javascript Array forEach provided functions can perform any kind of operation on the elements of the given array.

JavaScript forEach Array Method

Contents

  • JavaScript Array forEach() Method Syntax
  • forEach() Method Example
  • Output

JavaScript Array forEach() Method Syntax

array.forEach(function(currentValue, index, arr), thisValue)
  • currentValue In forEach method, value of the current element
  • index In forEach, array index of the current element
  • arr forEach array object the current element belongs to

forEach() Method Example 1

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

18 12 10 15

forEach() Method Example 2

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

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

document.writeln(newArr);
Output
// return

4,25,100,144

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

The JavaScript forEach functions code example here. We take a number array name num and it have used with forEach. This forEach functions return the simple values

Leave a Reply

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