1

Possible Duplicate:
What does the exclamation mark do before the function?
! preceding function in javascript?
javascript function leading bang ! syntax

I've been seeing this pattern a little bit recently in javascript:

!function () {
    // do something
}()

what does the bang in front of the function keyword supposed to do? I can't seem to find anything about it on the intertubez.

Community
  • 1
  • 1
hellatan
  • 3,171
  • 1
  • 24
  • 36

1 Answers1

1
function () {
    // do something
}();

This is an immediately invoked function declaration. A function declaration can not be immediately invoked; it is a syntax error.

To get around this syntax error, most people enclose the IIFD in parens to force it to be an expression instead (IIFE).

(function () {
    // do something
})();

In this case, they added an exclamation point instead.

jbabey
  • 42,963
  • 11
  • 66
  • 94
  • Indeed, I see this (the use of `!` in this manner) as a sign that the developer is so lazy that they decided typing one fewer character is worth the extra clock cycles to process the superfluous negation and the divergence from the common convention. :-) – Pete Sep 06 '12 at 15:11
  • @Pete: Not at all. I do this all the time, and not because I'm lazy. **It saves a byte on the wire.** Especially for mobile devices, it's important to minimize file size. Granted, it's only a byte, but bytes add up to better overall page performance and lower bandwidth bills. The superfluous negation thing is [complete bunk](http://jsperf.com/self-executing-style) and `!` is not as uncommon a convention as you'd think. – josh3736 Sep 06 '12 at 15:20
  • @josh3736 I can sort of buy the bandwidth bill argument, but some developers WAY overplay the "must save every byte for mobile devices!" argument. You have to remember that mobile devices are also super-underpowered computers. You're more likely to find someone with a cruddy CPU on a high bandwidth connection than the other way around. Saving requests is one thing (latency on mobile is terrible), but saving bytes is a tough sell. I think that saving a few CPU cycles is certainly worth an extra byte of transfer on a request that would happen either way. – Pete Sep 06 '12 at 15:30
  • I just ran [the performance test](http://jsperf.com/self-executing-style) on several mobile browsers: Safari iPhone and iPad, Android stock browser and Chrome Mobile, Opera Mobile, Firefox Mobile, and IE 9 Mobile (WP 7.5). Difference was *zero* on Android browsers and Firefox, and less than ±5% on the rest. (Curiously, `!` performed *better* on iPhone.) At any rate, you're still talking about something that gets several hundred thousand ops/sec, and realistically you'll only have a few ops *over a script's lifetime*. On mobile, balancing execution speed vs bandwidth, **saving bytes wins**. – josh3736 Sep 06 '12 at 16:14