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.