The forEach() method is an array method which is used to execute a function on each item in an array. We can use it with the JavaScript data types like Arrays, Maps, Sets, etc. It is a useful method for displaying elements in an array.
We can declare the forEach() method as below.
array.forEach(callback[, thisObject]);
The forEach() method executes the provided callback once for each element present in the array in ascending order.
1. callback: It is a function used to test for each element. The callback function accepts three arguments, which are given below.
2. thisObject: It is an object to use as this when executing the callback.
It will return the created array.
let apps = ['WhatsApp', 'Instagram', 'Facebook']; let playStore = []; apps.forEach(function(item){ playStore.push(item) }); console.log(playStore);
The corresponding JavaScript code is:
var apps = ['WhatsApp', 'Instagram', 'Facebook']; var playStore = []; apps.forEach(function (item) { playStore.push(item); }); console.log(playStore);
var num = [5, 10, 15]; num.forEach(function (value) { console.log(value); });
The following are the disadvantages of the use of the forEach() method: