Javascript - Function Expression (Anonymous function)

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

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;



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

4.2 - Expression directly used

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

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

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap