Javascript - Function Expression (Anonymous function)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

A Function Expression is just an function in the form of an expression stored generally in a variable that you execute by adding its signature ([param,[, param,[…, param]]])

A function expression is not created in the global context.

A function expression is a convenient way for creating closure. See Closure example

Advertising

3 - Named function expression

3.1 - Recursive expression

A named function expressions binds its name as a local variable within the function and allows so to write recursive function expressions.

Example with a count mathematical function.

var foo = function rec(v) {
   if (v <= 1) {
       v = 1;
   } else {
       v += " + "+rec((v-1));
    }
    return v;
}
mathExpression = foo(5);
console.log(mathExpression+ " = " + eval(mathExpression));

3.2 - Debugging

Javascript - (Debug|Diagnostic)

The name of the function expressions will be found in the stack traces.

4 - Example

4.1 - Expression stored in a variable

The below example binds the function to a variable 'add' rather than myOptionalName.

var add = function myOptionalName(x, y) {
   return x + y;
};
 
console.log(add(2,3))

where:

  • the function name (myOptionalName) is optional and default to _variableName (in this case add) inside the function (if recursivity is needed)

Advertising

4.2 - Expression directly used

The above can also be rewritten as a Immediately invoked function expression (IIFE).

console.log( 
     /* Parentheses means execute: here the function expression */
     (  function (x, y) { return x + y; } ) (2,3) /* Pass the variables 2 and 3 */
)

web/javascript/es/function_expression.txt · Last modified: 2019/06/05 12:40 by gerardnico