!function () {}();
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.
Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.
!
will negate (opposite) whatever you're expecting as a result, i.e if you havewhen you call
boy
, your result will betrue
, but the moment you add the!
when callingboy
, i.e!boy
, your result will befalse
. Which in other words you mean NotBoy, but this time it's basically a boolean result, eithertrue
orfalse
.That's the same thing that happens to the
!function () {}();
expression, running onlyfunction () {}();
will flag you an error, but add!
right in front of yourfunction () {}();
expression, makes it the opposite of thefunction () {}();
which should return youtrue
. Example can be seen below:Its just to save a byte of data when we do javascript minification.
consider the below anonymous function
To make the above as self invoking function we will generally change the above code as
Now we added two extra characters
(,)
apart from adding()
at the end of the function which necessary to call the function. In the process of minification we generally focus to reduce the file size. So we can also write the above function asStill both are self invoking functions and we save a byte as well. Instead of 2 characters
(,)
we just used one character!
The function:
returns nothing (or undefined).
Sometimes we want to call a function right as we create it. You might be tempted to try this:
but it results in a
SyntaxError
.Using the
!
operator before the function causes it to be treated as an expression, so we can call it:This will also return the boolean opposite of the return value of the function, in this case
true
, because!undefined
istrue
. If you want the actual return value to be the result of the call, then try doing it this way: