1. javascript
  2. /basics
  3. /advanced-iterations

Advanced Loops in JavaScript

Performance

Previously, we tackled repetitiveness in programming by understanding how the basics of iteration work. We went through several methods and saw some rudimentary examples of loops using:

  • The for loop

  • The for...in loop

  • The for...of loop

  • while loops

  • The do...while variation

Aside from simple control flow use cases, we can use these techniques practically, to loop through arrays and objects. Even though they're basic and straightforward, classic for loops may sometimes perform better, as other built-in methods can lead to slower performance due to unnecessary iterations.

For example, when working with smaller arrays, we may not need to worry about performance, but if the data structure grows in complexity and becomes nested, the extra iterations per function call will impact the overall performance of our code.

Advanced Looping in Arrays

Leveraging built-in methods such as map, reduce, and filter to iterate over arrays produces fewer lines in our code and makes it more clear and readable. We can transform elements, reduce them to a single value, and even filter out specific elements.

The map Method

First off, the map method creates a new array by transforming each element into the original one. Moreover, it takes a callback function as an argument, which is applied to each element in the array and returns a new value that is added to the new array.

Let's demonstrate that by converting an array of temperatures in Celsius to Fahrenheit:

const temperaturesCelsius = [10, 20, 30, 40];
const temperaturesFahrenheit = temperaturesCelsius.map(x => x * 9/5 + 32);
console.log(temperaturesFahrenheit); // [50, 68, 86, 104]

The reduce Method

The reduce method is a neat solution when you need to boil down an array of values into a single value. In the same manner, it applies a callback function to each element in the array and keeps track of the result in an accumulator.

For instance, here's how we can find the maximum value in an array:

const numbers = [5, 10, 15, 20];
const max = numbers.reduce((acc, cur) => Math.max(acc, cur), 0);
console.log(max); // 20

The filter Method

A filter method is a handy tool for creating a new array with only the elements that meet a certain condition.

In the example below, the method takes a callback function as an argument which is applied to each element in the array numbers. The function returns a boolean value indicating whether the element should be included in the new array.

With this, we can extract all even numbers from the original array:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(x => x % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]

Custom Functions for Looping over Objects

By default, objects are not iterable in JavaScript. As a workaround, we can create a custom function that loops over objects, which can be extremely beneficial if we want to maintain a specific order of the key-value pairs.

One way to do this is by using the Object.entries method to convert the object into an array of key-value pairs and then using the Map constructor to create a map from this array.

Here's an example of how you can use this method to loop over an object:

const food = new Map(
    Object.entries({ starter: 'salad', main: 'steak', dessert: 'cake'})
);

for (const v of food.values()) {
    console.log(v)
}

The output in the console would be:

salad
steak
cake

Additional Resources

Object Methods in JavaScript

Compressing For Loops with the forEach method