Javascript Q

Jake

Paragon
Joined
Nov 14, 2010
Messages
2,264
Reaction score
2
FP$
246
Hello, can anyone tell me why in tutorials this is used:

Code:
howManyDollars: function(amountOfMoney) {
		if(amountOfMoney < 1){
			return 0;
		}
		else {
			return 1.00+this.howManyDollars(amountOfMoney-1);
		}
}

instead of what I was thinking:

Code:
howManyDollars: function(amountOfMoney) {
  while(amountOfMoney!<1){
    return 1.00+(this.howManyDollars(amountOfMoney--);
  }
  return 0;
}

My method seems much more efficient...is there a reason to use recursion over a small while loop?

(Please note this is only a piece from an object, so it is not complete.)
 
I'd use the if() loop, because it gives a simpler way to change one part of the loop later - But that's personal preference.
 
Yeah, this is for a change finder. Feed it a price and what was paid and it goes through and tells you change in:

5 dollars,
dollars,
quarters,
dimes,
pennies
 
For a check that would happen only once in a function, you should use if. While says the loop should be executed over and over again. Since you return something inside while it will get terminated, else applying while condition on a static variable would end up in an infinite loop.

In your case, both the codes doesn't make much difference. But in your code, you should have amountOfMoney >= 1 instead of amountOfMoney !< 1.
 
Yeah, I realize how recursion would work better now. I was just pissed at the tutorial site @ not explaining why they chose to use recursion over a different loop-type.
Thanks for the replies.
 
Back
Top Bottom