JavaScript - forEach() method

Revision:


Category : array

The forEach() method calls a function for each element in an array. The forEach() method calls a function once for each element in an array, in order. forEach() is not executed for array elements without values.

The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

Syntax :

        array.forEach(callbackFn)
        array.forEach(callbackFn, thisArg)
        array.forEach(function(currentValue, index, arr), thisValue)
    

Parameters

callbackFn, function : required; a function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments:

element, currentValue : the (value of the) current element being processed in the array.
index : optional. The index of the current element being processed in the array.
array : optional. The array "forEach()" was called upon.

thisArg, thisValue : optional. A value to use as "this" when executing callbackFn. Default value "undefined".

Caveats

Don't use "async/await" within a forEach() callback.

Because a forEach() callback is a separate function, "await" can't be used without making the callback async.
Making a forEach() callback "async" would be a mistake, because then there will be unhandled promise rejections, because there's no way to handle errors.

forEach() is a method on JavaScript arrays and can't be used with array-like values, like function arguments or iterables.

When using forEach() with arguments or iterables, use "Array.from()" to convert to a fully fledged array first.

The forEach() method is a plain old JavaScript function, which means "looping constructs" like break or continue cannot be used.

Examples:

        const array1 = ['a', 'b', 'c'];
        array1.forEach(element => console.log(element));
        // Expected output: "a"
        // Expected output: "b"
        // Expected output: "c"
    

Practical examples

example: using forEach() method.


code:

                    <div>
                        <p class="spec" id="for01"></p><br>
                        <p class="spec" id="for01A"></p>
                        <p class="spec" id="for01B"></p>
                    </div>
                    <script>
                    let text = "";
                    const fruits = ["apple", "orange", "cherry"];
                    fruits.forEach(myFunc);
                    document.getElementById("for01").innerHTML = text;
                    
                    function myFunc(item, index) {
                        text += index + ": " + item + "<br>"; 
                    }
    
                    let sum_A = 0;
                    const numbers_A = [65, 44, 12, 4];
                    numbers_A.forEach(sumFunction);
                    document.getElementById("for01A").innerHTML = sum_A;
    
                    function sumFunction(item) {
                    sum_A += item;
                    }
    
                    function funct() {
                        // Original array
                        const items = [1, 29, 47];
                        const copy = [];
                
                        items.forEach(function (item) {
                            copy.push(item * item);
                        });
                        document.getElementById("for01B").innerHTML = copy;
                    }
                    funct();
                   </script>
                

example: updating array elements.

the forEach() method is used to iterate over an array, and it is quite simple to update the array elements.

examples




code:

                    <div>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for02"></p><br>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for02A"></p><br>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for02B"></p><br>
                    </div>
                    <script>
                    let students = ['John', 'Sara', 'Jack'];
                    students.forEach(updateFunction);
    
                    function updateFunction(item, index, arr) {
                        arr[index] = 'Hello ' + item;
                    }
                    document.getElementById("for02").innerHTML = students;
    
                    function func() {
                        // Original array
                        const items = [12, 24, 36];
                        const copy = [];
    
                        items.forEach(function (item) {
                            copy.push(item + item+2);
                        });
                        document.getElementById("for02A").innerHTML = copy;
                    }
                    func();
                    
                    const woorden = ['hello', 'bird', 'table', 'football', 'pipe', 'code'];
                    const capWords = woorden.forEach(capitalize);
                    
                    function capitalize(woord, index, arr) {
                        arr[index] = woord[0].toUpperCase() + woord.substring(1);
                    }
                    document.getElementById("for02B").innerHTML = woorden; 
                    console.log(woorden);
                    </script>
                

example: forEach() method with arrow function.

the ES6 arrow function representation can be used for simplifying the forEach() code.

examples



code:

                    <div>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for03"></p><br>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for03A"></p><br>
                    </div>
                    <script>
                        const studs = ['John', 'Sara', 'Jack'];
                        studs.forEach(element => {document.getElementById("for03").innerHTML = studs
                        console.log(element);
                        });
        
                        let ary = [1,2,3,4,5];
                        ary.forEach(i=>{document.getElementById('for03A').innerHTML += i + ", ";
                        console.log(i);
                        });
                    </script>
                

example: forEacht() method with sets

the forEach() method can be used to iterate through the Set elements.

The forEach() function of the Set object accepts the name of a particular function and runs that function for every value in the current set.

examples

code:

                    <div>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for05"></p>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for05A"></p>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for05B"></p>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for05C"></p>
                    </div>
                    <script>
                        const set = new Set([1, 2, 3]);
                        set.forEach(mySet);
        
                        function mySet(item) {
                            document.getElementById("for05").innerHTML += item + ", ";
                            console.log(item);
                        }
        
                        function sampleFunction(value){
                            document.getElementById("for05A").innerText +=  value +", ";
                        }
                        const setObj1 = new Set();
                        setObj1.add('Java');
                        setObj1.add('JavaFX');
                        setObj1.add('JavaScript');
                        setObj1.add('HBase');
                        setObj1.forEach(sampleFunction);
                        
                        let total_A = 0;
                        function mathExample(val) {
                            total_A = val + total_A;
                            // document.getElementById("for05B").innerHTMl = total;
                        }
                        const setObj2 = new Set();
                        setObj2.add(172);
                        setObj2.add(364);
                        setObj2.add(885);
                        setObj2.add(746);
                        setObj2.forEach(mathExample);
                        document.getElementById("for05C").innerText = "Sum of all elements in the set: " + total_A;
                        console.log(total)
                   </script>
    
                

example: forEach() method with maps.

the forEach() method can be used to iterate through the maps elements. The JavaScript map forEach() method executes the specified function once for each key/value pair in the Map object. The forEach function executes the provided callback once for each key of the map, which exists. It is not invoked for keys that have been deleted.

examples

code:

                    <div>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for06"></p>
                        <p class="spec" style="margin-left:5vw;margin-top: 1vw;" id="for06A"></p>
                    </div>
                    <script>
                        let map = new Map();
                        map.set('name', 'Jack');
                        map.set('age', '27');
        
                        map.forEach (myMap);
        
                        function myMap(value, key) {
                            document.getElementById("for06").innerHTML += key + " - " + value + ", <br>";
                            console.log(key + '- ' + value);
                        }
        
        
                        let mp = new Map();
                        // Adding values to the map 
                        mp.set("first", "Theo");
                        mp.set("second", "Staf");
                        mp.set("third", "Sander");
                        mp.set("fourth", "Jef");
                        mp.set("fifth", "Jan");
                        mp.forEach((values, keys) => {
                        console.log("values: ", values +
                            ", keys: ", keys + "\n")
                            document.getElementById("for06A").innerHTML += "values: "  + values + ", keys: " + keys + "<br>"  
                        });
        
                   </script>