-
Notifications
You must be signed in to change notification settings - Fork 2
JS Array Prototype ForEach
The forEach()
method executes a provided function once per array element.
Syntax
arr.forEach(callback[, thisArg])
-
callback Function to execute for each element, taking three arguments:
- currentValue The current element being processed in the array.
- index The index of the current element being processed in the array.
- array The array that forEach is being applied to.
-
thisArg Optional. Value to use as this when executing callback.
forEach()
executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialised (i.e. on sparse arrays). Unlike map()
or reduce()
it always returns the value undefined
and is not chainable. The typical use case is to execute side effects at the end of a chain.
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element);
}
// Note elision, there is no member at 2 so it isn't visited
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
// Create an array.
var numbers = [10, 11, 12];
// Call the addNumber callback function for each array element.
var sum = 0;
numbers.forEach(
function addNumber(value) { sum += value; }
);
document.write(sum);
// Output: 33
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links