Skip to content
Advertisement

Can someone explain this for/in loop to me?

/*
  Write each function according to the instructions.
  

  When a function's parameters reference `cart`, it references an object that looks like the one that follows.
  {
    "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 },
    "Pink Bucket Hat": { quantity: 2, priceInCents: 1260 }
  }
*/

function calculateCartTotal(cart) {
  let total = 0;
  for (const item in cart){
    let quantity = Object.values(cart[item])[0];
    let price = Object.values(cart[item])[1];
        total += price * quantity;
  }
 return total; 
}

function printCartInventory(cart) {
  let inventory = "";
  for (const item in cart){
    inventory += `${Object.values(cart[item])[0]}x${item}n`;
  }
  return inventory;
  
}

module.exports = {
  calculateCartTotal,
  printCartInventory,
};

The part that confuses me is the function calculateCartTotal. What I am confused about is how does this loop know to grab priceInCents? for example, if I was to add another value into the object called “weight: 24” assuming that it is 24 grams, how does the object value skip over quantity and weight and just grab priceInCents? Hopefully I am making sense on how I am confused and that someone has an explanation for me!

Advertisement

Answer

If you try to run below program then it will be easier for you to visualize everything.

What is happening is item is just the index of element and for an object we can either use the key name to access its value or its index.

You can read this doc to understand what Object.values() does.

function calculateCartTotal(cart) {
  let total = 0;
  for (const item in cart) {
    console.log(item)
    let quantity = Object.values(cart[item])[0];
    let price = Object.values(cart[item])[1];
        total += price * quantity;
  }
 return total; 
}

var cart = [
    {
        quantity: 2,
        price: 5,
        weight: 24
    },
    {
        quantity: 3,
        price: 10,
        weight: 90
    },
    {
        quantity: 7,
        price: 20,
        weight: 45
    },
    {
        quantity: 1,
        price: 100,
        weight: 67
    }
]

console.log(calculateCartTotal(cart))

OUTPUT:

0
1
2
3
280

Program 2 to demonstrate what is happening

function calculateCartTotal(cart) {
 console.log(Object.values(cart[2])[1])
 console.log(cart[2]['price'])
 console.log(cart[2].price)
}

var cart = [
    {
        quantity: 2,
        price: 5,
        weight: 24
    },
    {
        quantity: 3,
        price: 10,
        weight: 90
    },
    {
        quantity: 7,
        price: 20,
        weight: 45
    },
    {
        quantity: 1,
        price: 100,
        weight: 67
    }
]
calculateCartTotal(cart)

OUTPUT:

20
20
20
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement