1

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.");
 };
pavel
  • 24,015
  • 8
  • 38
  • 57
Chelsea
  • 649
  • 1
  • 5
  • 22
  • possible duplicate of [What is the difference between a function expression vs declaration in Javascript?](http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip) – Ali Habibzadeh Feb 03 '15 at 10:27
  • It's an [IIFE](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) – James Thorpe Feb 03 '15 at 10:27
  • possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – hina10531 Feb 03 '15 at 10:27

2 Answers2

2

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 () {}();
Jivings
  • 21,712
  • 6
  • 52
  • 95
0

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

Sagar Munjal
  • 572
  • 9
  • 11