The forEach function is an array method utilized to apply a specified function to every element within an array. It can be employed with various JavaScript data structures such as Arrays, Maps, Sets, and others. This method proves to be beneficial for rendering elements contained in an array.
Syntax
We can declare the forEach method as below.
Example
array.forEach(callback[, thisObject]);
The forEach function invokes the supplied callback for each element in the array sequentially, following an ascending order.
Parameter Details
- callback: It is a function used to test for each element. The callback function accepts three arguments , which are given below.
- Element value: It is the current value of the item.
- Element index: It is the index of the current element processed in the array.
- Array: It is an array which is being iterated in the forEach method.
Note: These three arguments are optional.
- thisObject: This refers to an object utilized as the context for 'this' during the execution of the callback function.
Return Value
It will return the created array.
Example with string
Example
let apps = ['WhatsApp', 'Instagram', 'Facebook'];
let playStore = [];
apps.forEach(function(item){
playStore.push(item)
});
console.log(playStore);
The corresponding JavaScript code is:
Example
var apps = ['WhatsApp', 'Instagram', 'Facebook'];
var playStore = [];
apps.forEach(function (item) {
playStore.push(item);
});
console.log(playStore);
Output:
Example with number
Example
var num = [5, 10, 15];
num.forEach(function (value) {
console.log(value);
});
Output:
Disadvantage of forEach
The subsequent points outline the drawbacks associated with the forEach method:
- There is no mechanism to terminate or exit the forEach loop.
- It is applicable exclusively to arrays.