0
  var test = function(x) {
         return x + 2;
    };

and I can use test(3)

but when I use

  var test = (function(x) {
         return x + 2;
    })();

I cannot use test(3)

why?

Adam Lee
  • 24,710
  • 51
  • 156
  • 236
  • because in the second example you are defining test as the return value, not the function – atmd Jan 23 '15 at 15:13
  • Because () executes function in runtime immediately, so test gets the result of function with no arguments (NaN). Then you are trying to run NaN as a function – Rax Wunter Jan 23 '15 at 15:14
  • You could do `var test = (function(x) { return x + 2; })(3);`, but that defeats the point of the function. – Andy Jan 23 '15 at 15:15

3 Answers3

0

The second code snippet is an example of an IIFE - Immediately-Invoked Function Expression.

The result of the expression inside the first set of parens defines a function that takes one parameter (named x). The second set of parens immediately invokes it, returning the result. Since you passed no arguments when invoking it, x is undefined so it evaluates the expression undefined + 2 and returns NaN.

mbcrute
  • 1,117
  • 1
  • 11
  • 19
0

In the first case you is defining a function, so you can do test(3)

In the second case you are executing a function, so, probably, you are getting NaN as the result.

Victor
  • 5,043
  • 3
  • 41
  • 55
0

In the second example, you're taking advantage of JavaScript closures. Closures allow you to control scoping and namespacing, and to declare private methods and variables.

Consider the following:

var test = (function() {
 var privateVar1;
 var privateVar2;

 function privateFunction() {
 }

 return {
    publicFunction1: function() {
    },
    publicFunction2: function() {
    }
 };
})();

test is now equal to the following:

{ publicFunction1: function() {}, publicFunction2: function() {} }

The function is immediately invoked after being declared, at which point x does not have a value. Initialize x before the function declaration (outside of its scope) to fix the problem you're experience:

var x = 10;
var test = (function(x) {
         return x + 2;
    })();
Ashwin Balamohan
  • 3,303
  • 2
  • 25
  • 47