What is the purpose of declaring a function like:
!function(){ code }();
Why the !
?
What is the purpose of declaring a function like:
!function(){ code }();
Why the !
?
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.
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: