Created
January 16, 2024 07:42
-
-
Save Nalini1998/c69568207236b9f3c4e32998fd029c2f to your computer and use it in GitHub Desktop.
The forEach() method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The forEach() method is used to loop through all elements of an array and calls a function (callback function) for each element in the array. The callback function has access to the current element, index, and the entire array on every loop. | |
``` | |
// Syntax | |
myArray.forEach(callbackFn) | |
myArray.forEach(function(element, index, array){ /* ... */ }) | |
``` | |
For example: | |
``` | |
let staff = [ | |
{ name: "John Doe", salary: 120 }, | |
{ name: "Jane Doe", salary: 350 }, | |
{ name: "Karl Don", salary: 710 } | |
]; | |
let totalSalary = 0; | |
staff.forEach(person => { | |
totalSalary += person.salary; | |
}) | |
console.log(totalSalary); | |
staff.forEach(person => { | |
let sentence = `${person.name} earns ${person.salary}` | |
console.log(sentence); | |
})` | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment