3

Possible Duplicate:
javascript function vs. ( function() { … } ());

I'm seeing this pattern in several of TodoMVC's JS source:

(function() {
    // ...
    // ...
}());

What's the specific meaning of this pattern? Note that it is not the self-invoking function which is (function() {})();

Community
  • 1
  • 1
gsklee
  • 4,774
  • 4
  • 39
  • 55

1 Answers1

8

What's the specific meaning of this pattern? Note that it is not the self-invoking function which is (function() {})();

You're incorrect, it is an Immediately Invoked Function Expression (IIFE). The parenthesis are just in a different place, but they bind the exact same way.

People often do it in the way you've described to get it to validate JSLint.

It's used for scoping, as JavaScript only has function and global scope (ignoring let).

alex
  • 479,566
  • 201
  • 878
  • 984
  • Is there any advantage wrapping the parenthesis this way over the other way around? – gsklee Aug 23 '12 at 02:10
  • @Kay One passes JSLint, one doesn't. If passing JSLint is important to you, then use the appropriate form. – alex Aug 23 '12 at 02:11
  • You ain't gonna get a more correct answer than this. The mention of JSLint makes it bulletproof. Damn that Crockford... always rearing his head in my text editor. – Cory Danielson Aug 23 '12 at 02:12