The code below is a function expression
: as the name uses the keyword expression
in its entirety it means that it is a value. It stays a value if it is just an expression and can be passed as any other value i.e. string
number
boolean
. However, it becomes a statement or declaration
if it is stored in a variable as a reference. Keep reading.
function () { }
You can also give a function expression a name and turn it into a named function expression
:
function foo() { }
The function name (foo, above) only exists inside the function and can, for example, be used for self-recursion:
Function declaration
or statement i.e. it is storing a value in a reference variable and here the reference variable is
var fac = function me(x) { return x <= 1 ? 1 : x * me(x-1) }
fac(10)
3628800
console.log(me)
ReferenceError: me is not defined
A named function expression is indistinguishable from a function declaration (which is, roughly, a statement). But their effects are different: A function expression produces a value (the function). A function declaration leads to an action – the creation of a variable whose value is the function. Furthermore, only a function expression can be immediately invoked, but not a function declaration.
credits : @rauschma
source-url : Expression vs Statements