Was trying to figure out how to properly namespace my JavaScript in order to avoid conflicts with other libraries as well as global items. I was reviewing some code and noticed something I just do not understand when it comes to JavaScript. In all reality I don’t even know how to ask the question so I will use some contrived code examples.
var varFuncTest = (function(){
_funcTest = function(params){
return "These are the params that were passed in: " + params;
};
return _funcTest;
})();
console.log(varFuncTest("params params params"));
OUTPUT: These are the params that were passed in: params params params
When I run this code it works as expected but that is only due to the fact that when I declared the variable I wrapped the function which is building and returning a specialized function in () and then added () right afterwards. When I log the function call I get the correct string printout.
Now when I remove that extra set of () from the end, because they looked unneeded to my untrained eyes, the log prints out the object type instead of the string.
var varFuncTest = (function(){
_funcTest = function(params){
return "These are the params that were passed in: " + params;
};
return _funcTest;
});
console.log(varFuncTest("params params params"));
OUTPUT: function()
What is going on here? Why is the second set of () needed? If this is a special function of the JavaScript language, what is it referred to and where can its documentation be found within the JavaScript API?
The code is identical minus the ending () on the 6th line of the first example. It is not a typo as it actually affects the execution within JavaScript. They both return a function object which is being assigned to the variable.
Javacript has the concept of an
immediately invoked function. This is a function that is called as soon as it is defined. These need to befunction expressionsinstead offunction statements.vs
Many of the answers given are true, or true-ish, but there is another aspect that none of them have mentioned.
When doing an assignment, such as
The outer-most level of parens are NOT needed by the compiler, but they server to inform the human reading the code that a immediately-invoked function is in place.
On the other hand, code like
the parens are needed to force the compiler to read an expression, and thus a
function-expression, rather than afunction statement.Using almost any other operator in front of the
functionkeyword works, such as:While that works, it isn’t the normal ‘idiom’ to-to-say of Javascript.
TL-DR: The parens are there more the sake of humans than computers.
BTW: Please stick with the standard coding conventions. There are a lot of non-standard-but-legal things you can do. Don’t. It confuses the person who comes after you.