What is the purpose of declare a function like! Function () {code} ();


This question already has an answer here:

  • What does the exclamation mark do before the function? 7 answers

What is the purpose of declaring a function like:

!function(){ code }();

Why the !?

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: