Using Loops in JavaScript Arrays

How to use the loop in JavaScript for arrays?

With over 5 years of experience in JavaScript, I’ve found the simplest way to loop over an array is by using a for loop. This classic approach allows you to iterate over each element and perform operations as needed.

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

In this example, the for loop goes through each element in the array and logs it to the console. It’s straightforward and easy to understand.

Building on what Alveera mentioned, another effective way to loop through an array is by using the forEach method, which I’ve used extensively in my projects. This built-in method executes a provided function once for each array element.

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

The forEach method simplifies the code by handling the iteration internally, and it makes the code cleaner and more readable.

Following up on Dimple’s approach, I’ve also found the for…of loop to be incredibly useful in modern JavaScript development. With over a decade of experience, I appreciate its concise syntax and readability.

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

The for…of loop is designed to iterate over iterable objects like arrays. It makes the code easier to read and write compared to traditional for loops, and it’s a great addition to your JavaScript toolkit.