ES6 | Array forEach() Method
When working with arrays, it’s widespread to iterate through its elements and manipulate them. Traditionally this can be done using for, while or do-while loops. The forEach will call the function for each element in the array.
array.forEach( callback, thisObject )
Parameter: This method accept only two parameter mentioned above and described below:
- callback: This allow the function to test the each and every element in the array.
- thisObject: This will be called when the callback function is executed.
Return: It returns the newly created array.
Without forEach() Loop: The first line declares and initialize a number array called array_1 with values [2, 3, 4, 5, 6]. To double every element of this array a for loop is used which runs from zero (because the index of an array starts from zero) to one less than the length of the array. Now on the third line, each element is extracted from the array and is multiplied by 2, hence doubling the values.
4, 6, 8, 10, 12
With forEach() Loop: In ES6 a more easy to understand and use method is introduced for Arrays which is forEach(). Let’s see how it works for the same above situation.
4, 6, 8, 10, 12
Same as previous, the first line declares and initialize a numbers array called array_1 with values [2, 3, 4, 5, 6]. Then on array_1 forEach method is called which iterates over the array and takes a callback function as an argument. Now the callback function accepts three arguments,
- currentValue – Which is a required argument, this corresponds to the value of the current element.
- index – It is an optional argument, this is the corresponding index value of the current element.
- array – It is also an optional argument, this is the original array, here array_1.
So, we make use of the second argument that is index and follow the exact same algorithm as before to double the value.
Program 3: Here we just use the currentValue argument using which we printout each of the values from names array to the console.
Arpan Abhishek GeeksforGeeks