How to forEach Over an Array in JavaScript

Answer: Use the forEach() Method

To loop through all items in an array, you can use JavaScript’s array’s  forEach() function. For each element of an array, the  forEach()  method executes a function once.

The following example will display all the values in the cities array using for each loop.

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

The  forEach()  method doesn’t modify the original array (i.e. the array it is called from). The callback function may, however, modify the original array if it is invoked. The following example modifies the array by quad-rating its values and multiplying it span>

<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>

arr.forEach(function callback(value, index, array){ // your iterator }. can give the basic syntax for the  forEach()  method. Three arguments are required to invoke the callback function: the element value and index, as well as the traversed array.

In the 5th edition of ECMAScript, the  forEach() function was added. This method is supported by all modern browsers such as Chrome, Firefox and IE9+.

Exit mobile version