Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke and define JavaScript function in same statement

Tags:

javascript

Is this the correct way:

(function() { 
   // do something here
}()); 

Or this way:

(function() { 
       // do something here
    })(); 
like image 943
ace Avatar asked Apr 16 '26 18:04

ace


1 Answers

It's only a difference in style, both are "correct." I prefer the second and would venture that it's more popular, some prefer the first.

What you can't do is simply

function() {
    // ...this example is wrong and won't work
}();

You need the parentheses in order to put the parser in the right mode that you're doing a function expression rather than a function declaration, but it doesn't matter whether the invoking parens at the end are within the main parens or outside them. You can try it with this live copy with the JavaScript engines in your favorite browsers...

like image 176
T.J. Crowder Avatar answered Apr 18 '26 08:04

T.J. Crowder