javascript interactive

JavaScript Interactive — a console crash course


3.2 Anonymous Functions

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
var f = function (value) {
    return 2 * value;
}

  
The function name can be omitted, creating an anonymous function. This is an example of a function expression, which can be handled just as other expression values. If stored in a variable...
>>>
f(1)
2
...the function call works just as when using a named function.
>>>
var g = f;

  
Since functions are first-class citizens, we can pass the function reference between variables. Or use it in any other situation where a normal value would be used.
>>>
g(2)
4
It doesn't matter which name is used when calling the function. This is sometimes used to abbreviate long function names.
>>>
var h = function () { return 1; };
function h() { return 2; };

  
>>>
h()
1
The above illustrates the difference between function declarations and function expressions (or statements). The named function variable is bound only once, at parse-time. But normal variables are statements, which are evaluated and bound at run-time (when the code is executed). Hence, a variable name can always shadow a named function.
>>>
(function () { return 4711; })()
4711
With the proper parentheses to avoid syntactic confusion, we can call an anonymous function immediately. This is a common pattern for doing one-off or initializer functions.
>>>

Index 1 2 3 4 5 6 7 8 9