yell
is a recursive function. When you call it with 4, it calls itself with 3 (4 - 1), which in turn calls itself with 2 (3 - 1), etc., as long as n
is > 0
.
The reason that yell
is available to be called in this way is that the person writing the code wrote a named function expression:
yell: function yell(n){
return n > 0 ? yell(n-1) + "a" : "hiy";
}
What that does is create a function with the name yell
, and assign it to the property yell
on the object ninja
. The property and the function happen to have the same name, but there's no reason they have to, it could have been:
yell: function foo(n){
return n > 0 ? foo(n-1) + "a" : "hiy";
}
yell
(the unqualified symbol), or foo
in my example above, is in scope within the function because it's the function's name.
It's worth a side-note here that named function expressions don't quite work correctly on IE8 and earlier (although that particular example would still work); more: Double take