JavaScript iterate Array | 5 Ways example codes

Iteration is the repetition of a process in order to generate an outcome. In JavaScript, you can iterate an array using for-loop, while-loop, foreach, every method, map, etc.

Examples of JavaScript iterate array

Let’s see HTML examples code:-

1. for loop

The for loop is used to iterate over a sequence. Let’s print all values of the array in the console.

<!DOCTYPE html>
<html>
<head>

    <script> 
        arr1 = [ 1, 2, 3, 4, 5 ]; 
        for (index = 0; index < arr1.length; index++) { 
            console.log(arr1[index]); 
        } 
    </script> 

</head>
<body>

</body>
</html>

Output:

JavaScript iterate Array

2. while loop

The while loop loops through a block of code as long as a specified condition is true.

<script> 
        arr1 = [ 1, 2, 3, 4, 5 ]; 
        while (index < arr1.length) { 
            console.log(arr1[index]); 
            index++; 
        }
    </script> 

3. forEach method

The forEach() method calls a function once for each element in an array, in order.

<script> 
        arr1 = [ 1, 2, 3, 4, 5 ]; 
        arr1.forEach(myFunction); 
        function myFunction(item, index) 
        { 
            console.log(item);  
        }
    </script>

4. every method

Every method executes the provided callback function once for each element present in the array until it finds the one where callback returns a falsy value.

<script> 
        arr1 = [ 1, 2, 3, 4, 5 ]; 
        const under_five = x => x < 5; 

        if (arr1.every(under_five)) { 
            console.log('All are less than 5'); 
        } 
        else { 
            console.log('At least one element is not less than 5'); 
        } 
</script> 

Output: At least one element is not less than 5

5. Using map

The Map object holds key-value pairs and remembers the original insertion order of the keys.

<!DOCTYPE html>
<html>
<head>

    <script> 
        arr1 = [ 1, 2, 3, 4, 5 ]; 
        square = x => Math.pow(x, 2); 
        squares = array.map(square); 
        console.log(array); 
        console.log(squares);
    </script> 

</head>
<body>

</body>
</html>

Output:

Examples of JavaScript iterate array

Note: In the first example only we used complete HTML code and output screenshot. You can do the same coding with others.

Do comment if you have another way to do it or have any doubts on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.