Loop through an array in JavaScript

This article will be very helpful if you are learning the JavaScript programming language and trying to write a custom code that manipulates or reads data in the Arrays.

A very common case in web development is that you need to iterate over some items in the array and perform a desired action, for example, when a specific value in the list equals to the predefined constant.

We will outline the most popular ways to go over the items in the array, you may choose the solution that is the most feasible and can be easily integrated into your code.

Option #1: For loop

This is the classic and widely used method of iterating over the list of data. Most of the programming languages support the "for" construct and JavaScript does it as well.

Although, you may need to use an additional variable to hold the index of the current item inside the loop. And the index must be incremented during each iteration, for this we use the "++" operator.

Please see below how it is implemented. Each value is printed into the console.

let letters = ['a', 'b', 'c', 'd', 'e'];

for (let i = 0; i < letters.length; i++) {
    console.log(letters[i]);
}

Also, as a part of this article, it is worth mentioning that the JavaScript supports two additional useful operators that can be used inside of a loop, they are the "continue" and "break" statements, they are described in the following paragraphs.

"continue" statement

You may use the "continue" statement to stop execution of the current iteration within the loop and to start the next iteration. This can be handy when you need to prevent some code from being run when some condition is met, like in the following example.

Please review the code below, the console log will not be printed if the current element within the loop equals to the letter "b".

let letters = ['a', 'b', 'c', 'd', 'e'];

for (let i = 0; i < letters.length; i++) {
    if (letters[i] === 'b') {
        continue;
    }

    console.log(letters[i]);
}

"break" statement

Also, at some point of time, it may be necessary to stop execution of the loop at all. The "break" statement can be used in that case. It will terminate the current iteration and will run the statement that is placed immediately after the loop.

If you run the following code, you'll see in the console that the letter is printed only once.

let letters = ['a', 'b', 'c', 'd', 'e'];

for (let i = 0; i < letters.length; i++) {
    console.log(letters[i]);
    break;
}

Option #2: While loop

We've modified our previous example to work also in the "while" loop. It's not that much different, but can be a good starting point if your intent is to write a complex logic and you need better control over the index value or the test condition statement.

Please see the code sample below:

let letters = ['a', 'b', 'c', 'd', 'e'];

let i = 0;
while (i < letters.length) {
    console.log(letters[i]);
    i++;
}

Option #3: Do while loop

This statement will execute your code only when the loop condition evaluates to true.

It's important to note that the first iteration will always run no matter what the result of the test condition, so please be careful with using this method.

The same as it's done in the previous methods, you need to manually control and increment the index variable for the loop to work correctly.

Following is the code sample that demonstrates how the "do…while" loop can be implemented.

let letters = ['a', 'b', 'c', 'd', 'e'];

let i = 0;
do {
    console.log(letters[i]);
    i++;
}
while (i < letters.length);

Option #4: forEach method

This solution may be a great choice if you are not willing to keep and process the index variable. The "forEach" method executes a specified function only once on each element of the specific array.

Please pay attention to the one important aspect of this method, the callback function will not be called on elements of the array which have been deleted or are simply not initialized. In other words, non-existent values are skipped, and callback will run only for the valid values.

Please review the example below. In our code, the arrow function is passed into the "forEach" method:

let letters = ['a', 'b', 'c', 'd', 'e'];

letters.forEach((element) => {
    console.log(element);
});

You can also specify the second argument in the callback function, it will contain an index of the current element within the array. This may be useful if you need to track position of some value.

let letters = ['a', 'b', 'c', 'd', 'e'];

letters.forEach((element, index) => {
    console.log('Current element: ', element);
    console.log('Index: ', index);
});

Optionally, you can also add the third argument to the callback, it will hold the original array. It allows you to read all array items within the callback function without the need to access the outer array variable.

let letters = ['a', 'b', 'c', 'd', 'e'];

letters.forEach((element, index, array) => {
    console.log('Current element: ', element);
    console.log('Index: ', index);
    console.log('Array: ', array);
});

Option #5: for…of statement

This statement can be used to loop over the given iterable object, such as Array, String, Map, Set, NodeList or TypedArray, etc.

This is a very simple and convenient method, please see below how to use it correctly.

let letters = ['a', 'b', 'c', 'd', 'e'];

for (const element of letters) {
    console.log(element);
}

Also, it is worth noting that you do not need to manually hold and increment the index property, as it's shown in earlier examples for the "for", "while", and "do…while" loops.

Option #6: for…in statement

This method isn't the best choice for iterating over the values in the given array, and you will read about it below. However, it's important to list the "for…in" method in this article to give you a deeper insight into the JavaScript programming language. As a result, you can choose the solution that is the most appropriate in your case and can be correctly added to the code.

The "for…in" method should be used to iterate over the enumerable properties of the specific object. It's not recommended to use it for regular arrays, as there is no guarantee that indexes will be returned in a particular order and the inherited properties will be enumerated as well.

In the following code, we define a very simple object, then iterate over the properties and print them to the console in a browser.

let book = {
    title: 'Web development',
    description: 'Learn how to make modern web applications',
    price: 19.99
};

for (const properly in book) {
    console.log(properly);
}

Option #7: map method

The "map" method can also be used to process each element of an array. The difference is that the "map" function will create a completely new array constructed of values returned by the passed callback function.

You can pass a regular or an arrow function that will receive a single array element as an argument.

In the following code, you can see how the data is modified.

let letters = ['a', 'b', 'c', 'd', 'e'];

let processed = letters.map(function(element) {
    return element + element
});

console.log(processed);

After running such a code, the console output will be as the following:

["aa", "bb", "cc", "dd", "ee"]

Conclusion

As you see, JavaScript has many language constructs that can help you in iterating over specific array. Some of the methods are very popular, like the "for", "while", "do…while" loops, and they are pretty straightforward. But other methods are only JavaScript specific and require good knowledge of various language constructs.

The solution that you choose should be compliant with the existing codebase and frameworks. Let's say, if other developers in a team use "forEach" function to iterate over the data, then it's wise to use the same method, so the other people are not confused with some new code.

Thank you for reading this article, please leave your questions or suggestions in the comment form below.

Leave a Reply

Your email address will not be published. Required fields are marked *