🟡 JS: Looping over Arrays 🟡

Looping over arrays is such a massive part of handling data in JavaScript that I wanted to cover some of the most common methods of doing so in this thread.

Let me know your favourite 💬 1/7

#100DaysOfCode #JavaScript #developers

1️⃣ For Loop

The for loop is one of the fundamentals of the language due to its versatility. It's no different when it comes to looping over an array.

The for loop works by creating a variable and incrementing it while a condition is true, we then access the index. 2/7

2️⃣ While Loop

A slightly more unusual way of looping through arrays is the while loop.

Similar to the for loop, the while loop will loop while a condition is true but unlike a for loop, it doesn't have a pre-determined end and instead will go forever while true. 3/7

3️⃣ .forEach()

More recently introduced to the language, the .forEach() method is built into the Array.prototype and allows for us to directly loop over an array without calling a loop explicitly.

In fact, it actually uses loops underneath but just makes the syntax simpler. 4/7

4️⃣ .map()

.map() is actually very similar to .forEach() with one key difference.

When using .forEach() we can only iterate through the array and not return anything. But, when we use .map() we can return values from the callback function as shown in the 🖼️. 5/7

👤 My Favourite

Personally, I always go for the .map() or .forEach() method depending on the situation, in general, I've moved away from traditional loops when it comes to looping through an array.

How about you? 💬 6/7