Home > Software design >  I am not understanding following javascript code, can anybody help me?
I am not understanding following javascript code, can anybody help me?

Time:11-13

I am learning javascript functions and I got following code which gives following output:

Output: "buy 3 bottles of milk" "Hello master, here is your 0 change"

function getMilk(money, costPerBottle) {
    console.log("buy "   calcBottles(money, costPerBottle)   " bottles of milk");
    return calcChange(money, costPerBottle);
}
function calcBottles(startingMoney, costPerBottle) {
    var numberOfBottles = Math.floor(startingMoney / costPerBottle);
    return numberOfBottles;
}
function calcChange(startingAmount, costPerBottle) {
    var change = startingAmount % costPerBottle;
    return change;
}
console.log("Hello master, here is your "   getMilk(6, 2)   " change");

I am not understanding what roles "startingMoney" and "startingAmount" plays here. Also how it is calculating number of bottles.

CodePudding user response:

So you have three functions, the first of which getMilk is defined on top, but called as part of console.log parameter evaluation.

Hence, before the program writes anything it calls getMilk and the first thing it does is print string "buy 3 bottles of milk" to console. The 3 is important because it is calculated by calling calcBottles which returns the result of dividing the total money by price per bottle.

Then the program continues and calls calcChange which returns the remainder of total money and price per bottle, which in this case is 0, which when returned to original caller results in string "Hello master, here is your 0 change" being printed.

CodePudding user response:

The number of bottles is calculated as follows: data is entered in the form of the amount of money available and the price per bottle, then the money is divided by the amount per bottle, so we get the number of bottles that the buyer can buy. And Math.floor rounds the resulting number of bottles down from fractional to integer.

CodePudding user response:

startingMoney and startingAmount represent the total money available and the number of bottles is calculated as total money by amount of per bottle.

CodePudding user response:

Both are the sames. It is the money that you pass into getMilk function.

If you have the total money and the cost per unit of bottle, you can calculate:

How many bottles can you buy using the total money (calcBottles function)

And the change if the total money cannot be divided by the unit cost of a bottle (calcChange function)

  • Related