Skip to content Skip to sidebar Skip to footer

What Determines If A Javascript Function Is A Named Anonymous Function Versus A, Um, Regular Function?

Reading 'A re-introduction to JavaScript' I noticed something interesting about functions: The name provided to an anonymous function as above is(or at least should be) only avail

Solution 1:

The first is a normal function declaration. The declared name is introduced into the current scope, and implicitly refers to the function body. In this form, function is a statement, and as such returns no value.

The second is a function expression, and the interpreter knows that because it's part of the right hand side of an assignment, and because of the braces around it. Any time the word function appears where some other "value" (or "expression") could have been supplied then what you have is a function expression. The result of that expression is a reference to the function body.

The name of a function expression (if it were given one) is only available within the function, as described in your link.

IMHO the nomenclature in that link is incorrect. What they call a "named anonymous functions" should in my view just be called a "named function expression". This apparent error may stem from the fact that all anonymous functions are actually function expressions, but not all function expressions are anonymous.

Note that if you use this style:

var foo = function bar() {
    ...
}

then as described above bar is a function expression, whose result is then assigned to the variable foo. The name bar is not put into the current scope, but is available within the function itself.

The declaration of the variable foo will be hoisted to the top of the scope, but will not be assigned its value (i.e. the reference to the function expression) until the line above is actually executed.

Another interesting demonstration of the difference is this (from the Chrome console):

> function() { }
SyntaxError: Unexpected token (
> a = function() { }
function () { }

Note that the only difference is that in the latter there is an assignment to a. The attempt to declare an anonymous function using a statement is illegal, because the language grammar requires that the function statement include a label for the function. However the latter is implicitly a function expression, which is allowed to be anonymous.

Post a Comment for "What Determines If A Javascript Function Is A Named Anonymous Function Versus A, Um, Regular Function?"