What do empty parentheses () after a function declaration do in javascript? [duplicate]

The code is defining an anonymous function (the (function (){ ... }) bit) and then calling it (with no arguments). It then assigns the value to the Browser property of the object that is presumably being defined outside of your code snippet.

You could also define the function somewhere:

function myFunction() {
    var ua = navigator.userAgent;
    var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
    return {
      IE:             !!window.attachEvent && !isOpera,
      Opera:          isOpera,
      WebKit:         ua.indexOf('AppleWebKit/') > -1,
      Gecko:          ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
      MobileSafari:   /Apple.*Mobile.*Safari/.test(ua)
}

and then call it:

var foo = myFunction();

and then assign the value:

...
Browser: foo,
...

One downside with doing it that way is that you “pollute your namespace” with a function and a variable that you won’t use anywhere else. The second issue is that you can’t use the value of any locally-scoped variables in your function definition (the anonymous function behaves as a closure).

Leave a Comment