Skip to content
Advertisement

Can someone explain this for/in loop to me?

JavaScript

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.

JavaScript

OUTPUT:

JavaScript

Program 2 to demonstrate what is happening

JavaScript

OUTPUT:

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