How to forEach Over an Array in JavaScript ?

How to forEach Over an Array in JavaScript?

Asked on October 31, 2018 in Javascript.
Add Comment


  • 1 Answer(s)

      Use the array’s forEach() method to loop through all the items in an array using JavaScript. The forEach() method executes a provided function once for each array element.

    For ex:

    <script>
      // Sample array
      var cities = ["London", "Paris", "New York", "Amsterdam"];
      // Loop over array
      cities.forEach(function(value)
    {
        document.write("<p>" + value + "</p>");
      });
    </script>
    

      If the callback function was invoked,The forEach() method  modify the original array otherwise it does not alter,like this:

    <script>
      // Sample array
      var numbers = [1, 2, 3, 4, 5, 6];
      // Loop over array and squaring each value
      numbers.forEach(function(value, index, array){
        array[index] = value * value;
      });
      console.log(numbers); // Prints: [1, 4, 9, 16, 25, 36]
    </script>
    

      The basic syntax of the forEach() method can be given with arr.forEach(function callback(value, index, array){ // your iterator }. The callback function is invoked with three arguments: the element value, the element index, and the array being traversed.

    Answered on October 31, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.