Loops

JavaScript have many types of loops, the traditional for-loop, do..while loop, for in/of loop.

They are very useful in certain scenarios where needed, but in modern JavaScript it's generally recommended, to use Array loop methods where possible.

This is because you avoid mutation or 'side-effects', and they convey clarity.

For Loop

for loops are great for when you need to something unrelated to an array, like counting or doing something for X amount of times.

alt

JS

Copy

for (let i = 1; i <= 3; i++) {
    console.log(i)
}
// 1
// 2
// 3

If you want to manipulate arrays, using a for loop can have side effects, and using Array loop methods, are recommended.

For example consider the following code snippet;

JS

Copy

const numbers = [1,2,3,4];

for (let i = 0; i < numbers.length; i++) {
    numbers[i] = numbers[i] * 2;  //side effect mutating the original array!
}

console.log(numbers); // [ 2, 4, 6, 8 ]

As you can see we're mutating the original list, to avoid it, we'd have to use clunky code like creating a new list, and pushing to it.

The simpler solution is to use Array loop methods