Console Learner — An interactive JavaScript course.


3.2 Anonymous Functions

>>>
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 g = (value) => 2 * value;

  
Using the => arrow function syntax (since ES6), anonymous functions can be created with less code (i.e. without using the function or return keywords, etc). Other differences will be explained later.
>>>
var h = function () { return 1; };
function h() { return 2; };


  
>>>
h()
1
The above illustrates an important difference between function declarations and function expressions. 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 has been a common pattern for doing one-off initializer functions.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.