Skip to content
the poor coder

loop over an array

Poor Man
Published
Reading time
2 min read
On this page

Loop Over an Array#

As a web developer, I have encountered many situations where I needed to loop over an array in JavaScript. Looping over an array means to iterate through each element of the array and perform some operation on it. Here are a few ways to loop over an array:

1. For Loop:#

The simplest way to loop over an array is by using a for loop. Here is an example:

JavaScript

        let array = [1, 2, 3, 4, 5];
        
        for(let i = 0; i < array.length; i++) {
            console.log(array[i]);
        }
    

In the above example, we have an array with five elements. We are using a for loop to iterate through each element of the array and log it to the console.

2. ForEach Loop:#

The forEach() method is another way to loop over an array. It is similar to the for loop, but it provides a more concise syntax. Here is an example:

JavaScript

        let array = [1, 2, 3, 4, 5];
        
        array.forEach(function(element) {
            console.log(element);
        });
    

In the above example, we are using the forEach() method to iterate through each element of the array and log it to the console.

3. For-Of Loop:#

The for-of loop is a new feature in JavaScript ES6. It provides a more concise syntax than the for loop and the forEach() method. Here is an example:

JavaScript

        let array = [1, 2, 3, 4, 5];
        
        for(let element of array) {
            console.log(element);
        }
    

In the above example, we are using the for-of loop to iterate through each element of the array and log it to the console.

Conclusion:#

In conclusion, there are multiple ways to loop over an array in JavaScript, such as using a for loop, forEach() method, and for-of loop. Each method has its own advantages and disadvantages, depending on the use case. It is up to the developer to choose the best method for their specific situation.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC