Methods of looping through an Array in JavaScript

Published on 2022-02-15

This article will deliver you a good overview of how, where, and when we can use multiple looping techniques in JavaScript.

JavaScript

JavaScript (abbreviated as JS) is a computer language that, together with HTML and CSS, is one of the most important technologies on the Internet. On the client-side, over 97 percent of websites utilize JavaScript to manage web page behavior, along with the usage of third-party libraries.

What is JavaScript Array?

A JavaScript array is a collection of numerous types of values. It can be a collection of strings, numbers, objects, or a combination of the three. But its value has the same processor. Looping an array is the process of iterating through an array to determine its value. You may build an array in JavaScript by assigning an array literal to a variable. A JavaScript array can be iterated in a variety of ways. The easiest way is to use the “for each” method to loop through an array.

This is how an array looks like

// declare an array
let array = [1, "abc", 2, "loop", 3, "iterate"]

Looping Through an Array in JavaScript

Every developer has to deal with arrays on a regular basis. We will look at a few alternative techniques of iterating over arrays in JavaScript.

“forEach” Loop Method

The forEach method accepts the following parameters and returns a callback function for each array entry:

  • Current value (required) - The value of the current array element
  • The index number of the current element (optional)
  • The array object that the current member is a part of (optional)

Let us go through each of these aspects one by one.

Let’s see an Array.forEach method in action.

Array.forEach(function(element, current_index, current_array){
    // your code goes here
})

Now let’s go to the code section that demonstrates how to iterate through an array using forEach.

// declare an array
let array = [1, " abc ", 2, "loop", 3, "iterate"]

// javascript forEach in ES5
array.forEach(function(elem, index, array){
    // iterate through an array using forEach loop
    console.log(index+ " element is "+elem)
})

=>
0 element is 1
1 element is abc
2 element is 2
3 element is loop
4 element is 3
5 element is iterate

Using the aforementioned approach, not only a simple array but also an array of objects may be looped over. We don’t need to define or increment a variable to access the next index of an array when we use forEach. forEach() is best used to iterate over array elements without breaking and to have additional benefits at the same time. Examples these include a mutation of an outer scope variable, I/O operations (HTTP requests), DOM changes, and so forth. For example, let’s select all input components from the DOM and clear them with forEach().

const inputs = document.querySelectorAll('input[type="text"]');
inputs.forEach(function(input) {
    input.value = '';
});

“for” Loop Method

The simplest sort of loop is the “for” loop. It is made up of three primary parts, as described below:

When we submit a value to the totaler at the outset of the loop, the initialization phrase is executed first, before the loop starts. A condition is evaluated to see if it is true or false using the test statement. The loop’s function is performed if the condition is met; else, the control exits the loop. It is possible to increase or reduce the totaler using the iteration statement. On a single line, semicolons could be used to divide all three elements.

In JavaScript, the for loop is written in the following form:

for (initialization; test condition; iteration statement) {
    Statement(s) to be executed if the test condition is true
}

Array.map() Method

Array.map() iterates across an array and modifies it based on the condition. The Array.map() feature was added in an ECMA Script called ES5.

Let’s have a look at how the Array.map() technique works in practice.

Array.map(function callback(currentValue, currentIndex, mainArray) {
    // Return new array
})

Now we’ll loop through an array and alter it. The function Array.map() always returns a new array.

// declare an array
let array = [1, 2, 3, 4]

// javascript Array.map() in ES5
let new_array = array.map(function(elem, index, array){
    return elem = elem * 2
})

// original array
console.log(array)
=> [ 1 , 2 , 3 , 4 ]

// new modified array
console.log(new_array)
=> [ 2 , 4 , 6 , 8 ]

Using jQuery.each()

The JQuery.each() or $.each() function may traverse across any collection, whether it be an object or an array, invisibly. Because the $.each() method obtains and employs the “length” attribute of the given array or object.

<DOCTYPE html>
<html>
    <head>
        <title>Loop through array with jQuery.each()</title>
        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var colors = ["Blue", "Red", "Orange", "Green", "Blue"];
                $.each(colors, function(index, value){
                    $("#colors").append(index + ": " + value + '<br>');
                });
            });
        </script>
    </head>
    <body>
        <div id="colors"></div>
    </body>
</html>

Using Array.filter() Method

As it iterates across the target array, the filter() method accepts a callback function and executes it for each item in the array. The callback function accepts the following parameters:

  • currentItem: The array element that is being iterated over at the moment.

  • index: The index position of the currentItem inside the array.

  • The target array and all of its elements are represented by this array.

The filter method generates a new array and returns all objects that satisfy the callback’s requirements.

Examples

Let’s check some of the examples to understand this all in a better way:

Example #1

let people = [{ name: "aaron", age: 65 }, { name: "beth", age: 15 }, { name: "cara", age: 13 }, { name: "daniel", age: 3 }, { name: "ella", age: 25 }, { name: "fin", age: 16 }, { name: "george", age: 18 }]
let range = { lower: 13, upper: 16 }

let teenagers = people.filter(function(person) {
    return person.age >= this.lower && person.age <= this.upper;
}, range)

console.log(teenagers)

=>
[{ age: 15,  name: "beth" }, { age: 13,  name: "cara" }, { age: 16,  name: "fin" }]

Example #2

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var total;
            document.write("Starting Loop" + "<br />");
            for(total = 0; total < 10; total++) {
               document.write("Current Total : " + total );
               document.write("<br />");
            }
            document.write("Loop stopped!");
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

=>
Starting Loop
0 in total
1 in total
2 in total
3 in total
4 in total
5 in total
6 in total
7 in total
8 in total
9 in total
The loop has come to an end!

Change the value of the variable and try again…

Example #3

// declare an array of object
let array = [
    {
        name : "abc",
        value : 12
    },
    {
        name : "jsArray",
        value : 21
    },
    {
        name : "loop",
        value : 16
    },
    {
        name : "jsArray",
        value : 10
    }
]

// javacript Array.filter() in ES5
let new_array = array.filter(function(elem, index, array) {
    return elem.value > 15
})
// new modified array
console.log(new_array)

=>
    [
        {
            name : "jsArray",
            value : 21
        },
        {
            name : "loop",
            value : 16
        },
    ]

Example #4

<!DOCTYPE html>
<html>
    <head>
        <title>Loop through array with jQuery.each()</title>
        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var colors = ["Blue", "Red", "Orange", "Green", "Blue"];
                $.each(colors, function(index, value){
                    $("#colors").append(index + ": " + value + '<br>');
                });
            });
        </script>
    </head>
    <body>
        <div id="colors"></div>
    </body>
</html>

=>
0: Blue
1: Red
2: Orange
3: Green
4: Blue

Example #5

let team = [
    {
        name: "aaron",
        position: "developer"
    },
    {
        name: "beth",
        position: "ui designer"
    },
    {
        name: "cara",
        position: "developer"
    },
    {
        name: "daniel",
        position: "content manager"
    },
    {
        name: "ella",
        position: "cto"
    },
    {
        name: "fin",
        position: "backend engineer"
    },
    {
        name: "george",
        position: "developer"
    }
    ]

let nondevelopers = team.filter(member => member.position !== "developer")
console.log(nondevelopers)

=>
[
    {
        name: "beth",
        position: "ui designer"
    },
    {
        name: "daniel",
        position: "content manager"
    },
    {
        name: "ella",
        position: "cto"
    },
    {
        name: "fin",
        position: "backend engineer"
    }
]

Conclusion

Hence, there are various approaches for learning how to loop in an array in JavaScript. We just made use of JavaScript’s advantages and capabilities. The array.forEach(callback) function provides a quick way to iterate over all of the objects in an array. Its first parameter is the callback function, which is called with three arguments: item, index, and the array itself, for each of the items in the array. forEach() is handy for iterating over all array elements without breaking and causing any side effects at the same time.

Otherwise, there are certain different approaches for iterating over array as well. The filter() array function returns item(s) that match the callback expression after filtering them out with the respective expression. In terms of performance, they’re all equivalent at the end of the day. The only difference is your own preference, with a few tiny outliers.