5

What is the purpose of declaring a function like:

!function(){ code }();

Why the !?

GoTo
  • 5,966
  • 2
  • 28
  • 31
  • Can you post a more detailed example? – uncoder Apr 28 '14 at 23:28
  • This is an IIFE (immediately invoked function expression). For info on why you might use one see this article: http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – jfriend00 Apr 28 '14 at 23:31

2 Answers2

4

It tells the interpreter that the function keyword following is part of a function expression rather than a declaration. This allows the function to be executed immediately, creating a namespaced, encapsulated module.

A more common approach is to wrap the function keyword and body in parens. This is sometimes called an 'IIFE' or module pattern.

Jimmy Breck-McKye
  • 2,923
  • 1
  • 22
  • 32
3

In JavaScript, you can declare and execute a function in one shot, but doing it like this:

function() { /* ... */ }();

is a syntax error.

You can make it work by forcing the parser to recognise the function declaration as part of an expression rather than as a statement:

(function() { /* ... */ }());

What you're seeing is an alternative way of doing this, by using the ! operator. It'll negate the function's result but, here, that result (if there is one) is ignored anyway.

!function() { /* ... */ }();

In other words, it's a bit of a hack.


Further reading:

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055