Is there a difference in using the Sum (as you go) or as I have done below when doing the 'Shop' exercise?


I used this:

alert(“Hi, welcome to the shop”);
var Bread = 2;
var Milk = 1.5;
var Cheese = 4;
var Yoghurt = 1.2;
var a = (prompt(“How much bread do you want?”));
var b = (prompt(“How much milk do you want?”));
var c = (prompt(“How much cheese do you want?”));
var d = (prompt(“How much yoghurt do you want?”));
console.log(“The total amount to pay is $”,+ (aBread)+(bMilk)+(cCheese)+(dYoghurt));

Which works, however, Ivan put this:

var​bread =​2​;
var​milk =​1.5​;
var​cheese =​4​;
var​yogurt =​1.2​;
var​sum =​0​;
alert(​"Hi! Welcome to the Ivan on Tech Shop!"​);
var​input = prompt(​"How much bread do you want?"​);
sum += input * bread;
var​input = prompt(​"How much milk (liter) do you want?"​);
sum += input * milk;var​input = prompt(​"How much cheese do you want"​);
sum += input * cheese;
var​input = prompt(​"How many yogurts do you want?"​);
sum += input * yogurt;
console​.log(​"The total amount to pay is"​, sum);

Is there a difference or efficiency between either approach, i.e would mine build up more technical debt by creating additional variables in the memory? This is one of the reasons I believe mine is less efficient, perhaps!

Thanks, just wondering as it works anyway :slight_smile:

1 Like

Hey @Luis_Elliott, hope you are well.

Your codes looks good, clean indentation always help to understand quickly.

Both code methods are complete valid, just keep in mind that ivan have to explain some fundamental stuffs on the lessons, so its code might not be the most efficient, also this is exactly the beauty of coding, there will be always room for another solution, is just about efficient code at the end.

Now continuing the example, the sum variable is just to save the total amount of the products, it could be useful if you improve even more the exercise to something that need to calculate the total amount of products (sum), that way, would be easier to call the variable instead coding the sum of all of them (compare your last console.log with ivans code for example).

the point is, if you need to reuse a value or code, it would be great to create a additional variable.

Carlos Z