Im reading John Resigs “Learning Advanced JavaScript” http://ejohn.org/apps/learn/#10 and came across this function below that I don`t understand.
The function yell is called with an argument of 4. When this is done, the argument 4 is run through the terniary operator. If it is greater than zero, which it is, then we come to yell(n-1) + a
My questions relate to this.
a) does yell(n-1) + a call the function again (i.e. restart it) with an argument of 3.
b) If you do (n-1) + a, you get a result of 3a. Does JavaScript convert 3a to “aaa”. I ask this because in the assert line it says yell(4) == "hiyaaaa"
c) after converting it, does it somehow add it to “hiy”? I don`t understand how.
d) if JavaScript does convert 3a to a string of “aaa”s, and somehow manages to add it to “hiy”, I don`t understand why yell(4)=hiyaaaa. Yell(n-1) + a = hiyaaa (3as), not hiyaaaa(4″a”s).
As you can see I am totally confused.
function yell(n){
return n > 0 ? yell(n-1) + "a" : "hiy";
}
assert( yell(4) == "hiyaaaa", "Calling the function by itself comes naturally." );
a) This function is taking advantage of recursion, so yes, the function called again and everything else is pushed on the stack waiting for that return value.
b) No, the function is called with a return value as mentioned above.
c) See Above.
d) It doesn’t.
Think of it like this:
If you call b(“hiya”) you’ll get hiyaaa. Now instead of calling a different function, call the same one.