Saurabh Palatkar Saurabh Palatkar - 5 months ago 19
Javascript Question

What's the difference between below two code styles

Code1:

var x=(function(){
return {
greet:function(){
alert('Hello from code1');
}
};
})();


Code2:

var x=function(){
return {
greet:function(){
alert('Hello from code2');
}
};
}();


Both will be invoked like:

x.greet();


In the style 1 I've enclosed the self executing function within parenthesis while in the second code it is not. Both work same.
So what is the difference between code1 and code2 and which is remanded way?

Answer

There is no practical difference. Some people prefer one way over the other, similar to the preference for putting opening braces on the same line or the next line, or tabs vs spaces, or writing x=1+2 instead of x=(1+2).

Extra parentheses can add clarity, or clutter, depending entirely on style preference.