What is the purpose of declaring a type function! Function () {code} ();

What is the purpose of declaring a function such as:

!function(){ code }();

Why !?

+4
source share
2 answers

In JavaScript, you can declare and execute a function in one shot , but execute it as follows:

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

is a syntax error.

You can make it work by making the parser recognize the function declaration as part of the expression, and not as an operator :

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

What you see is an alternative way to do this using an operator !. This negates the result of the function, but here this result (if any) is ignored in any case.

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

In other words, this is a bit of a hack.


Further reading:

+2

, function , . , .

, parens. IIFE .

+4

Source: https://habr.com/ru/post/1538493/


All Articles