Currently, I am immersing myself in the world of JavaScript by taking courses on CodeAcademy.com. However, there is one exercise question that is giving me some trouble, even though I believe I have come up with the correct answer.
This particular code is intended to assist individuals in determining how much change they should return when a purchase is made. It takes a number as input and then calculates the appropriate amount of quarters and pennies to give back.
My confusion lies here:
• Shouldn't the code cease running the first time it reaches line 11? If not, could you explain why?
• In case the code does indeed stop at line 11, why am I able to insert additional code after line 10 which executes three times before providing an output? Upon testing this, I realized that indeed, placing quarters += 1;
after line 10 results in a return value of 6.
var change = 0;
var quarters = 0;
function howManyQuarters(howMuchMoney) {
if (howMuchMoney < 0.25) {
change = howMuchMoney;
return 0;
}
else {
quarters += 1;
howManyQuarters(howMuchMoney-0.25);
return quarters; // << line 11
}
}
change = 0.99;
console.log ("Pay out " + howManyQuarters(change) + " quarters");
console.log ("And you'll have " + change * 100 + " pennies left over");