[ACCEPTED]-what does !function in Javascript mean?-javascript
It is short-hand or alternative of self-invoking anonymous function:
(function(){
// code
})();
Can 8 be written:
!function(){
// code
}();
You can also use +
instead of 7 !
.
If you simply did:
function(){
// code
}();
That will create problems, that's 6 why you need to add !
before it which turns 5 the function declaration into function expression.
An ExpressionStatement cannot 4 start with the function keyword because that 3 might make it ambiguous with a FunctionDeclaration.
To 2 better understand the concept, you should 1 check out:
they're negating the result, not the function 6 itself:
!function( x ){ return x }( true );
!true
false
In reality, it's a slightly compressed 5 form of:
(function(){}())
since it requires 1 less character. The 4 reason it's needed is that you can't call 3 a function declaration directly, e.g. this 2 is invalid:
function(){}()
but adding the !
at the beginning 1 turns it into a function expression
and makes it work.
It's usually used to work around a quirk 6 in the JavaScript syntax. This gives a syntax 5 error:
function() {
}();
It's read as a function declaration 4 (like function foo () {}
), rather than a function expression. So 3 adding the ! before it, or wrapping it in 2 parentheses, forces the parser to understand 1 that it's an expression.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.