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
Articles Related
Named function expression
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));
Debugging
Javascript - (Debug|Diagnostic)
The name of the function expressions will be found in the stack traces.
Example
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)
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 */
)