How to use Javascript array forEach function

Description

forEach() accepts two arguments:

  • a function to run on each item and
  • an optional scope object

forEach() runs the given function on every item in the array. forEach() has no return value.

The function passed in receives three arguments:

  • the array item value,
  • the position of the item in the array
  • the array object itself.

It is the same as iterating over an array with a for loop.

Example


var numbers = [1,2,3,4,5,4,3,2,1]; 
        /* ww  w  . j  av  a2 s.com*/
numbers.forEach(function(item, index, array){ 
   console.log(item);
}); 

The code above generates the following result.

forEach() does not change the values contained in the array.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window