3

While looking via some modules sources for node.js I have found one having the following construction:

;(function(global){

    var a = // some definitions
    .. // code



})(typeof window === "object" ? window : this);

So what is the meaning to write:

  1. semicolon in front of code?
  2. to write (typeof window === "object" ? window : this); ?
kaytrance
  • 2,657
  • 4
  • 30
  • 49

1 Answers1

8

The semicolon is a safety measure for minifications (elaborated on here).

The second part of your question: (typeof window === "object" ? window : this) is checking whether the code runs in a browser. If window is actually defined, then we conclude it runs in a browser, if not it runs in node. Then we pass this environment (node.js or window) as a variable.

Community
  • 1
  • 1
MeLight
  • 5,454
  • 4
  • 43
  • 67
  • 1
    +1 The semicolon also hinders collisions between modules, if somebody helds to the style of writing with "Automatic Semicolon Insertion"...[citation needed] – loveNoHate Mar 11 '14 at 12:36
  • 1
    @dollarVar no citation, but here is an example: `var a = 42 /*newline*/ (function(){})()` results in TypeError: number is not a function – Tibos Mar 11 '14 at 13:26
  • 1
    @Tibos Ok, I throw something in: http://www.ecma-international.org/ecma-262/5.1/#sec-12. Look at the NOTE...seems like `IIFE` is not that welcome by ECMA :/ About the `ASI` thing here: http://www.ecma-international.org/ecma-262/5.1/#sec-8 (scroll up to the last *The Source*;) – loveNoHate Mar 11 '14 at 14:04