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?
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?
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.
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;
})();