7 ms·
A cleaner way to convert a function declaration into a function expression would be to use brackets (function() { //code here })(); This won't affect
by usablebytes 12y ago
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.
- dhimes 12y agoThis 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.
- tothepixel 12y agoTo 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);
- thekingshorses 12y agoThis reduces size after uglifying. (function(window, $, otherGlobal) { $ = window.jQuery; otherGlobal = window.otherGlobal; //code here })(window);
- deleted 12y ago[deleted]
- adambard 12y agoThis 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 !.