Array forEach

In this chapter you will learn:

  1. How to use Javascript array forEach function

Array forEach()

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.

<!DOCTYPE html><!--   j a  v a 2s.c o  m-->
<html>
<head>
    <script type="text/javascript">
        var numbers = [1,2,3,4,5,4,3,2,1]; 
        
        numbers.forEach(function(item, index, array){ 
            document.writeln(item);
        }); 
        //
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

The code above generates the following result.

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

Next chapter...

What you will learn in the next chapter:

  1. How to use array as a stack
  2. How to use push and index to add value to an array
Home » Javascript Tutorial » Array
Array Type
Array creation
Array type detecting
Array iterate
Array Length
Add to Array
Array join
Array concat()
Array every method
Array search from start with indexOf()
Array search from the end with lastIndexOf()
Array filter
Array mapping
Array forEach
Array pop and push
Array shift()
Array reduce()
Array reduceRight()
Array reverse()
Array slice()
Array some()
Array splice()
Array sort()
Array toString()
Array unshift()