Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A cleaner way to convert a function declaration into a function expression would be to use brackets

  (function() {
    //code here
  })();
This won't affect the return type of the statement; which in case of using ! will return boolean 'true' unless the function returns a truthy value. Plus using ! for this purpose, looks totally messy.


To extend upon this, you can also pass in references to decrease lookup time. That's why you see people doing:

   (function($,window) {
     //code here
   })(jQuery,window);


This reduces size after uglifying.

  (function(window, $, otherGlobal) {  
     $ = window.jQuery;
     otherGlobal = window.otherGlobal;

     //code here
  })(window);


This solves one of the problems that '!' does, but not the other. If this file is concatenated with one that looks like it would accept a function call, it will be an error, because javascript. e.g.

    (function(){/* stuff */}())
    (function(){/* other stuff */}())
Is interpreted as:

    (function(){/* stuff */)())(function(){/* other stuff */}())
To correct this, you also need a semicolon.

    ;(function() {
        //code here
    })();
Alternatively, if you can stomach it (I can't), you can use the !.


This is what I use- in fact, I've been confused by this thread because I've never seen the '!' hack before. Even though someone called in "javascript syntax 101." I must be using good sources to learn.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: