The forEach() method executes a provided function once for each array element.
Syntax
arr.forEach(function callback(currentValue [, index [, array]]) {
//your iterator
}[, thisArg]);
- callback - Function to execute on each element, taking three arguments:
- currentValue - The current element being processed in the array.
- index (Optional) - The index of the current element being processed in the array.
- array (Optional) - The array forEach() was called upon.
- thisArg (Optional) - Value to use as this when executing the callback.
Examples
Example 1: Simple Array.forEach() Example
var progLangs = ['Java', 'C', 'C++', 'PHP', 'Python'];
progLangs.forEach(element => {
console.log(element);
});
Output:
Java
C
C++
PHP
Python
Example 2: Converting a for loop to forEach
const items = ['item1', 'item2', 'item3'];
const copy = [];
// before
for (let i=0; i<items.length; i++) {
copy.push(items[i]);
}
// after
items.forEach(function(item){
copy.push(item);
});
Comments
Post a Comment
Leave Comment