PDA

View Full Version : Resolved Javascript (function() {}); and function() {};



keyboard
09-09-2012, 06:18 AM
What's the difference between -


onload = (function() {

});

and


onload = function() {

};

Thanks, keyboard1333

djr33
09-09-2012, 06:55 AM
When parentheses are not required, they are always optional (as far as I know). In other words, if you don't need parentheses, you can choose to add them if you wish.

For example:
if (((a==b))) {...

They can sometimes make the code easier to read, or make sure that a statement isn't ambiguous. For example:
if (a==b||c==d&&e==f) {...

In that case, the code is valid, but it's unclear exactly how the logic works out. So adding some parentheses can help.

Of course there are other cases where they're strictly required, such as when you're calling a function and adding arguments.



In short, unless I'm missing something, those two are exactly equivalent.

keyboard
09-13-2012, 03:02 AM
Thanks Daniel!

bernie1227
09-13-2012, 08:40 AM
I tend to add parentheses, when it is something that I want to make clearer for readability, ie, in if statements:


if($i == ($j / ($z + ($a - 5))){
}