Reputation: 751
While learning javascript I came across function statement and function expression.
function fun(){} // function statement
var fun = function() {} //function expression
Then I came accross this example explained as function expression.
(function() {
alert("I am a function");
}());
Is this really a function expression? It appears as a function statement to me as
function() {
alert("I am not a function statement.");
};
Upvotes: 1
Views: 452
Reputation: 774
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
Upvotes: 0
Reputation: 23260
Wrapping the function in parentheses makes it an expression.
This is because in JavaScript parentheses cannot contain statements, so the engine knows to parse an enclosed function as an expression.
The same would be true if you used any other other operation that only operates on an expression:
(function () {}());
!function () {}();
+function () {}();
~function () {}();
void function () {}();
Upvotes: 2