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 Array.map() to Change Values

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

// apply a 10% discount
const discountApplied = expensiveItems.map( 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.

Subscribe

Get more great content like this, enter your email below.

Share

Loading comments...

Leave a comment

Your email address will not be published. Required fields are marked *