javascript function leading bang ! syntax

javascript function leading bang ! syntax

I’ve been seeing this syntax on a few libraries now and I’m wondering what the benefit is. (note i’m well aware of closures and what the code is doing, I’m only concerned about the syntactical differences)
!function(){
// do stuff
}();

As an alternative to the more common
(function(){
// do stuff
})();

for self invoking anonymous functions.
I’m wondering a few things. First off, what is allowing the top example to actually work? Why is the bang necessary in order to make this statement syntactically correct? I’m told also that + works, and I’m sure some others, in place of !
Second, what is the benefit? All I can tell is that it saves a single character, but I can’t imagine that’s such a huge benefit to attract numerous adopters. Is there some other benefit I”m missing?
The only other difference I can see would be the return value of the self invoking function, but in both of these examples, we don’t really care about the return value of the function since it’s used only to create a closure. So can someone tell me why one might use the first syntax?

Related:  How and why does 'a'['toUpperCase']() in JavaScript work?

Solutions/Answers:

Solution 1:

Ideally you should be able to do all this simply as:

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

That means declare anonymous function and execute it. But that will not work due to specifics of JS grammar.

So shortest form of achieving this is to use some expression e.g. UnaryExpression (and so CallExpression):

!function(){
  // do stuff
}(); 

Or for the fun:

-function(){
  // do stuff
}(); 

Or:

+function(){
  // do stuff
}(); 

Or even:

~function(){
  // do stuff
  return 0;
}( );

Solution 2:

In Javascript, a line beginning with function is expected to be a function statement and is supposed to look like

function doSomething() {
}

A self-invoking function like

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

doesn’t fit that form (and will cause a syntax error at the first opening paren because there is no function name), so the brackets are used to delineate an anonymous function expression.

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

But anything that creates an expression (as opposed to a function statement) will do, so hence the !. It’s telling the interpreter that this is not a function statement. Other than that, operator precedence dictates that the function is invoked before the negation.

Related:  Select2 Ajax Method Not Selecting

I wasn’t aware of this convention, but if it becomes common it may contribute to readability. What I mean is that anybody reading the !function at the top of a large block of code will expect a self-invocation, the way we are conditioned already to expect the same when we see (function. Except that we will lose those annoying parentheses. I would expect that’s the reason, as opposed to any savings in speed or character count.

Solution 3:

Besides the things that were already said, the syntax with the ! is useful if you write javascript without semicolons:

var i = 1
!function(){
  console.log('ham')
}()

i = 2
(function(){
  console.log('cheese')
})()

The first example outputs ‘ham’ as expected, but the second will throw an error because the i = 2 statement isn’t terminated due to the following parenthesis.

Also in concatenated javascript files you don’t have to worry if the preceding code has missing semicolons. So no need for the common ;(function(){})(); to make sure your own won’t break.

I know my answer is kind of late but i think it haven’t been mentioned yet:)

Related:  How to make a jQuery plugin loadable with requirejs

Solution 4:

For one thing, jsPerf shows that using ! (UnaryExpression’s) are usually faster. Sometimes they come out to be equal, but when they aren’t, I haven’t seen the non-banged one triumph too much over the others yet: http://jsperf.com/bang-function

This was tested on the latest Ubuntu with the oldest (per say..) Chrome, version 8. So results may differ of course.

Edit: How about something crazy like delete?

delete function() {
   alert("Hi!"); 
}();

or void?

void function() {
   alert("Hi!"); 
}();

Solution 5:

So, with negate “!” and all other unary operators like +,-,~, delete, void, a lot has been told, just to sum up:

!function(){
  alert("Hi!");
}(); 

Or

void function(){
  alert("Hi!");
}();

Or

delete function(){
  alert("Hi!");
}();

And a few more cases with binary operators for fun 🙂

1 > function() {
   alert("Hi!"); 
}();

Or

1 * function() {
   alert("Hi!"); 
}();

Or

1 >>> function() {
   alert("Hi!"); 
}();

Or even

1 == function() {
   alert("Hi!"); 
}();

Leaving the ternary for someone else guys 🙂

Solution 6:

As you can see here, the best way to do self-invoked methods in javascript is using:

(function(){}()); -> 76,827,475 ops/sec

!function(){}();  -> 69,699,155 ops/sec

(function(){})(); -> 69,564,370 ops/sec