I'm trying to gain a deeper understanding of how Javascript works and the following code is bugging me:
function notInVar(a, b) {
return a + b
}
var inVar = function doesThisWork(a, b) {
return a + b
}
document.writeln('2 + 2 = ' + notInVar(2, 2));
document.writeln('3 + 3 = ' + inVar(3, 3));
document.writeln('4 + 4 = ' + doesThisWork(4, 4));
In Chrome, the first two document.writelns execute as expected, then I get "Uncaught ReferenceError: doesThisWork is not defined"
in Chrome. Why can't I call the second function by the name doesThisWork
? For that matter, where is the first function-object notInVar stored?
The second definition is called a named function expression and due to the nature of that definition, the only way you can call it by name is from inside the function body:
var inVar = function doesThisWork(a, b) {
return doesThisWork(a + b); // infinite recursion!
}
This can be used to achieve recursion inside an otherwise anonymous function, without having to use something like the Y-combinator.
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