Don’t Use a For Loop, Use These Instead

The for loop is something you’ll use all the time to iterate over an array. It works, but there are better Javascript methods you can use to make your code more concise.

Disadvantages of a normal for loop:

  • It encourages mutating the existing array
  • You have to create a new variable (i)
  • It’s ugly and verbose

First, let’s look at a typical for loop, then we’ll see how we can improve it. Assume we have an array of objects called products.

// in the cart we have an array of product objects
// we want to loop over the cart items, get the cart total and cart count
// we also want to grab any items over $100 to apply a discount
let cartSubTotal = 0;
let cartCount = 0;
let cartTotalWithTax = 0;
let expensiveItems = [];
for( let i = 0; i < products.length; i++ ) {
  cartSubTotal = cartSubTotal + products[i].price;
  cartCount = cartCount + products[i].quantity;
  cartTotalWithTax = cartTotalWithTax + products[i].price + getTax( products[i].price );
  // save expensive items to a new array so we can apply a special discount
  if( product[i].price > 99 ) {
    expensiveItems.push( product[i] );

This code will get us the cart total, item count, and the total with tax, but it’s a bit verbose. Here are 3 methods that will achieve the same thing with less code.

Use Array.reduce() When You Want a Number

If you want to get a single number like a cart total, reduce() is the juice.

const cartCount = products.reduce( ( total, item ) => total + item.quantity, 0 );

You’ll notice the 0 as the second argument, this is the initial value for total. If we don’t add this, it will use the first array item, which is an object, and break our code.

We can do the same for the sub total and total with tax.

const cartSubTotal = products.reduce( ( total, item ) => total + ( item.price * item.quantity), 0 );
const cartTotalWithTax = cartSubTotal * 1.1; // adds 10% for tax

Use Array.filter() to Grab a Few Items

What if we want to only grab the products that are over $100 and apply a special discount? We can use filter() for that.

// first, create a new array only with products at $100 or more
const expensiveItems = products.filter( product => product.price > 99 );

Use to Change Values

Next we want to discount the price by 10% on the expensive items. We can do this using

// apply a 10% discount
const discountApplied = product => {
  let retObj = product;
  retObj.price = retObj.price * .9;
  return retObj;

With methods like reduce, filter, and map, should we ever use a normal for loop? Rarely, if ever. You can almost always replace a for loop with one of these or another method.

1 comment

  1. Map, filter, and reduce is the way! Master these 3 array methods and you level-up as a JavaScript developer

Comments are closed.