In a book I'm reading, there is a page about recursion with the following code:
var hanoi = function hanoi(disc, src, aux, dst){
if (disc > 0){
hanoi(disc - 1, src, dst, aux);
document.writeln('Move disc ' + disc + ' from ' + src + ' to ' + dst);
hanoi(disc - 1, aux, src, dst);
}
};
Edit: Question rephrase - In this example, what is the difference between var hanoi = function hanoi(){} and just using var hanoi = function(){} ?
E.g. why is Hanoi being declared as the variable, but also the function is being named Hanoi? Why the double up of 'hanoi'?
There's a very subtle point at play here. In the following two examples, the body of the function is the same as your original. In one case, an anonymous function is used, while in the other, the function is named "hanoi" just as in the original.
var hanoi2 = function hanoi(disc, src, aux, dst){
if (disc > 0){
hanoi(disc - 1, src, dst, aux);
document.writeln('Move disc ' + disc + ' from ' + src + ' to ' + dst);
hanoi(disc - 1, aux, src, dst);
}
};
var hanoi3 = function(disc, src, aux, dst){
if (disc > 0){
hanoi(disc - 1, src, dst, aux);
document.writeln('Move disc ' + disc + ' from ' + src + ' to ' + dst);
hanoi(disc - 1, aux, src, dst);
}
};
Will either of these work? Note that the body of the function is still referring to "hanoi", not "hanoi2" or "hanoi3".
It turns out that hanoi2 will work, but hanoi3 will not. This is because when you name a function, the name of the function is available inside the scope of the function body. So, in both your original example and in hanoi2, the "hanoi" inside the function isn't referring to the global variable hanoi but rather the named function hanoi.
So, the answer to your question is that because the function uses recursion, the named version is slightly more robust than the anonymous version under modifications to your code.
var hanoi = function hanoi(){} creates a Named Function Expression and assigns it to a variable which name happens to be the same as the expression name.
function hanoi(){} declares a function.
There are difference in the way those two constructs are hoisting. For example you can call declared function before the declaration. But you can't do the same with named function expression.
//ok
var joe = new Person();
function Person() {};
//error
var joe = new Person();
var Person = function Person(){};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With