...

/

Tip 21: Write Shorter Loops with Array Methods

Tip 21: Write Shorter Loops with Array Methods

In this tip, you’ll learn to reduce long loops to single lines with array methods.

Using loops

Before we begin, I want you to know that for loops and for...of loops are good. You’ll want to use them, and you should use them. They’re never going away.

But you should use them less. Why? Well, the reason is simple: They’re unnecessary clutter. You’re writing modern JavaScript, which means you’re going for simplicity, readability, and predictability, and traditional loops don’t meet those goals. Array methods do. Mastering array methods is the fastest way to improve your JavaScript code.

Example

Look at this basic loop that converts an array of price strings into floating-point values.

Press + to interact
const prices = ['1.0', '2.15'];
const formattedPrices = [];
for (let i = 0; i < prices.length; i++) {
formattedPrices.push(parseFloat(prices[i]));
}
console.log(formattedPrices);

It’s short, sure. The whole thing takes four lines. Not bad. But consider a file that has five functions. And each function has a loop. You just added 20 lines to the file.

And this function is pretty short to begin with. What if you had an array that contained some non-numerical strings and you wanted only parsable numbers? Your function starts to grow.

Press + to interact
const prices = ['1.0', 'negotiable', '2.15'];
const formattedPrices = [];
for (let i = 0; i < prices.length; i++) {
const price = parseFloat(prices[i]);
if (price) {
formattedPrices.push(price);
}
}
console.log(formattedPrices);

The problem with using loops

Clutter. Clutter. Clutter. Just look at all the extra stuff you need just to get the float ...

Access this course and 1400+ top-rated courses and projects.