Skip to content

Instantly share code, notes, and snippets.

@Nalini1998
Created January 16, 2024 07:42
Show Gist options
  • Save Nalini1998/c69568207236b9f3c4e32998fd029c2f to your computer and use it in GitHub Desktop.
Save Nalini1998/c69568207236b9f3c4e32998fd029c2f to your computer and use it in GitHub Desktop.
The forEach() method
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