In JavaScript, what is the advantage of !function(){}() over (function () {})()?

Andrew Hedges picture Andrew Hedges · Sep 28, 2011 · Viewed 8.9k times · Source

Possible Duplicate:
What does the exclamation mark do before the function?

I've long used the following for self-executing, anonymous functions in JavaScript:

(function () { /* magic happens */ })()

Lately, I've started seeing more instances of the following pattern (e.g., in Bootstrap):

!function () { /* presumably the same magic happens */ }()

Anyone know what the advantage is of the second pattern? Or, is it just a stylistic preference?

Answer

Peter Olson picture Peter Olson · Sep 28, 2011

These two different techniques have a functional difference as well as a difference in appearance. The potential advantages of one technique over the other will be due to these differences.

Concision

Javascript is a language where concision can be very important, because Javascript is downloaded when the page loads. That means that the more concise the Javascript, the faster the download time. For this reason, there are Javascript minifiers and obfuscators that compress the Javascript files to optimize the download time. For example, the spaces in alert ( "Hi" ) ; would be optimized to alert("Hi");.

Keeping this in mind, compare these two patterns

  • Normal closure:   (function(){})() 16 characters
  • Negated closure: !function(){}() 15 characters

This is a micro-optimization at best, so I don't find this a particularly compelling argument unless you are doing a code golf contest.

Negating the returned value

Compare the result value of a and b.

var a = (function(){})()
var b = !function(){}()

Since the a function does not return anything, a will be undefined. Since the negation of undefined is true, b will evaluate to true. This is an advantage to people who either want to negate the returned value of the function or have an everything-must-return-a-non-null-or-undefined-value fetish. You can see an explanation for how this works on this other Stack Overflow question.

I hope that this helps you understand the rationale behind this function declaration that would typically be considered an anti-pattern.