How to use JavaScript array foreach

In this article, I am going to explain use of array foreach() in JavaScript.
  • 2054

The array foreach method of JavaScript

The JavaScript foreach method  executes a user-defined function for each element of an array.

Syntax of array foreach element

array.foreach(callback[, thisArgs);

Parameters in array foreach  method:

  • arrary

    Array required an array object.

  • callback

    Callback function accepts up to three arguments, and callback function is used to test  for each element

  • thisArgs

    ThisArgs is used as this when executing callbacks.

Return value in foreach method

Foreach  method returned a newly created array.

Exception in foreach  method

If callback argument is not a function object, A TypeError exception is fire.

There are the following callback function parameter:

Parameter Value
value Array element value.
index Numeric  index of the array element.

Example of foreach method





    <form id="form1" runat="server">

    <script type="text/javascript">

    var numbers = [10, 10, 10];


    // Call the addNumber callback function for each array element.

    var sum = 0;


    function addNumber(value) { sum += value; }






    <asp:Button ID="Button1" runat="server" Text="Button" />





Ask Your Question 
Got a programming related question? You may want to post your question here


More Articles

© 2018 DotNetHeaven. All rights reserved.