Do you know all the possible way to loop in JavaScript? 🔃

Riccardo Bertolini
7 min readJul 23, 2023

--

Which kind of looping do you use? Do you know the implication cost-wise and performance for each one of them?
Looping in JavaScript is a fundamental aspect of the language: developers have various techniques at their disposal, each with its own strengths and weaknesses — let’s dive in with some example and a final thought.

So either that you’re a seasoned developer or a new entry in this world, it’s important to have a good idea of all the tools available on your belt, so it will be eaier to use the right one at the right moment. 🙂

How to handle a clone attack without getting infinite loops? — Credits Phil Shaw on Unspash

1. for loop

A for loop is perhaps the most common looping mechanism in JavaScript: it’s straightforward and provides fine-grained control over the looping variables and conditions, making it familiar and intuitive to many developers.

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

However, it’s not without its downsides: it can lead to off-by-one errors if you’re not cautious with the indices and requires manual handling of the control variable. Probably perfect for simple iteration, it has been less and less used in favor of array manipulations.

2. for...in Loop

The for
in loop, on the other hand, finds its utility when iterating over the properties of an object: it grants access to both property names and values within the loop, which can be handy. However, it also loops over all enumerable properties, including those inherited through the prototype chain. This feature can sometimes cause confusion and unexpected behavior. Furthermore, the order of iteration isn’t guaranteed, which could be problematic in certain scenarios.

let obj = {a: 1, b: 2, c: 3};

for (let prop in obj) {
console.log(`${prop}: ${obj[prop]}`);
}

3. While loop

While loops form one of the fundamental pillars of control flow in JavaScript; these loops continuously execute a block of code as long as the specified condition holds true. By allowing repeated execution of code snippets, while loops offer developers the convenience of not having to manually write out repetitive commands.

let index = 0;
const data = [{item: 1}, {item: 2}, {item: 3}, {item: 4}];
while (index < data.length) {
console.log(index);
index++;
}

This loop prints the items from 0 to 4 on the console.

When is best to use them? While loops are excellent when the total number of iterations required isn’t known in advance, since they’re simple and straightforward, providing a smooth avenue for developers to embed repetition in their code logic. On the downside, incorrect handling of while loops (especially regarding the terminating condition) can lead to infinite loops and potentially crash a program, so be careful!

4. Do-While loop

Following the same spirit of code repetition is the do-while loop, we can see it as close relative of the while loop but with an important difference: it checks the condition at the end of the loop. This unique feature means that the loop’s code block will be executed at least once, irrespective of the condition.

let index = 0;
do {
console.log(index);
index++;
} while (index < 5);

Similar to while loops the numbers 0 to 4 will be printed at least once.

Why should I use a do-while? On the plus side, the do-while loop’s assurance of at least a single execution can be a powerful tool when writing interactive programs where user input is involved. However, if not correctly implemented, do-while loops can also lead to the dreaded infinite loop, making it pretty dangerous and force the application to crash.

5. ForEach loop

The forEach() method is an inbuilt array function in JavaScript that helps developers execute a given function for each item in an array — personally, my favorite method since it’s safe and flexible.

let quizScores = [85, 90, 78, 92, 88];

console.log("Announcing quiz scores:");

quizScores.forEach(function(score, index) {
console.log(`Student ${index + 1}: ${score}`);
});

console.log("End of announcement. Keep up the good work, everyone!");

This will print each score in the array on a new line.

The forEach() method is concise and efficient for array iteration, perfect when handling arrays. However, it doesn’t work with break or continue statements, which can limit its versatility — so the developers cannot handle fully the iterations behaviors. Additionally, the forEach() method doesn’t return a value, which might be unexpected for developers used to functions that return values and the risks to create not pure function is higher.

6. Map() loop

This is a surprise right? Well Map is indeed a loop as well, and it’s another function that works on arrays. It creates a new array with the results of calling a provided function on every element in the calling array, and that’s the main difference with the forEach() method.

let tasksCompleted = [1, 2, 3, 4, 5];
let playerLevels = tasksCompleted.map(function(tasks) {
return tasks * tasks;
});

console.log("Player levels:");

playerLevels.forEach(function(level, index) {
console.log(`Player ${index + 1}: Level ${level}`);
});

console.log("Keep leveling up, gamers!");

In this case, the map() function is iterating through the tasksCompleted array and returning a new array (playerLevels) where each element is the square of the corresponding element in the original array. This represents the level of each player in the game. After this, the forEach() function is used to log the level of each player.

The map() method is particularly useful for transforming an array. It always returns a new array, which can be beneficial for maintaining the immutability of the original array. However, this aspect can also be a downside if the original array is large, as it may lead to higher memory usage.

7. For
of loop

Everytime I see this loop, it brings me back to the PHP era — the for
of loop is a modern addition to JavaScript, introduced in ES6 and has been designed for iterating over iterable objects, including arrays, strings, maps, and others.

let treeTypes = [1, 2, 3, 4, 5];
let treeNames = ["Oak", "Maple", "Pine", "Willow", "Cherry"];

console.log("Welcome to our Tree Tour!");

for (let type of treeTypes) {
console.log(`Stop ${type}: The beautiful ${treeNames[type - 1]} Tree`);
}

console.log("End of the tour. Hope you enjoyed the beauty of our park's diverse trees

In this example, the for
of loop is iterating over each element of the treeTypes array, logging a message for each tree type during the tour, and the array treeNames is used to fetch the name of the tree corresponding to the current type.

The for
of loop is simple and straightforward, working with any iterable object (yes, any!) but it doesn’t work with non-iterable objects, which limits its usefulness in certain scenarios, so it’s important to cover those cases with a proper condition.

8. Reduce loop

The reduce() method in JavaScript is a powerful array function designed for transforming and condensing arrays into a single value and it works by iteratively applying a reducing function to each element of the array, from left to right, and accumulating the returned values into a single result. The reducing function takes the accumulated value so far and the current array element as its arguments.

const bookPrices = [12.99, 15.99, 8.5, 20, 5.99];
const totalCost = bookPrices.reduce(function(total, price) {
return total + price;
}, 0);

console.log(`The total cost of all the books is: $${Math.floor(totalCost)}`);

In this case, the reduce() function is being used to sum all the prices in the bookPrices array: it starts with an initial total of 0, and for each iteration, it adds the current book price to the total. Finally, it logs the total cost of all the books to the console.

One of the primary strengths of the reduce() function is its versatility: it can be used to transform an array into virtually any kind of output for example a single value, a new array, an object, etc.
reduce(), however, can be a bit more challenging to understand and use correctly than some of the other array methods due to its complexity since its behavior can be difficult to predict without a firm grasp of how it accumulates values and how the reducing function works.

9. Special Mentions

There are some loops that I haven’t mentioned since even if classified as loops are not the one you’ll use to manipulate objects in a loop but for something specific rather than handling each single entry in a collection.

  • filter() used to creates a new array with all elements that pass a test implemented by the provided function.
  • some() tests whether at least one element in the array passes the test implemented by the provided function.
  • every()checks whether all elements in the array pass the test implemented by the provided function.
  • find() and findIndex() return the first value or index that passes a test, respectively.
  • Array.from() if you’re an array fan, this method creates a new array instance from an iterable or array-like object. Not everyone knows that it takes as its second argument a map function, allowing for iteration over the created array.
  • Set and Map iteration: If you're working with JavaScript's Set or Map data structures, you can use their native .forEach methods, or iterate over them with for...of.

JavaScript is a remarkable programming language, and in my opinion, one of the reasons lies in its capacity to evolve and adapt to emerging needs. The numerous loop methods it provides serve as testament to this, simplifying the manipulation and handling of data as necessitated by different situations. Happy coding đŸ’»đŸ€–đŸ‘šđŸ»â€đŸ’»đŸ‘©đŸ»â€đŸ’»

--

--