Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does function name disappear when assigned to a var?

Tags:

javascript

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?

like image 624
Ian Durkan Avatar asked Jul 03 '13 02:07

Ian Durkan


1 Answers

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.

like image 191
Ja͢ck Avatar answered Oct 09 '22 18:10

Ja͢ck