so how do we interpret this?
If we print this out it is like this below, why? because an anonymous function is undefined, and !undefined is true, we don't care whether it returns true or false but care that the JavaScript engine can parse it perfectly.
!function(){alert('sd')}() // true
But you may wonder how does an anonymous function can call itself with no error.
We normally see the below formats more frequently :
(function(){alert('123')})() // true (function(){alert('123')}()) // true
Anyway whichever format it is, its main purpose to put a bracket around is to turn a function declaration into an Expression which can be parsed/ Run. for example
function a(){alert('zsd')} // undefined
This is a function declaration if we put a bracket behind directly, JavaScript Engine certainly doesn't understand. so Syntax error will come.
function a(){alert('iifksp')}() // SyntaxError: unexpected_token
This code makes the engine confused between function declaration and function call. However, putting a bracket around is different, it turns a function declaration into an expression, the engine will understand it is no more a function declaration but an expression, So this expression will be called when the code is run into this line.
In short, Any grammar that can help to make the engine clearly differentiate function declaration and expression will be accepted by Javascript. For example:
var i = function(){return 10}(); // undefined 1 && function(){return true}(); // true 1, function(){alert('as')}(); // undefined
Assignment Operators, Logic Operators, and even a comma can tell then engine that this is not a function declaration but a function expression. The unary operator is said to be the fastest way to clear the ambiguity for the engine, exclamation mark (!) is just one of them. here come some examples:
!function(){alert('as')}() // true +function(){alert('as')}() // NaN -function(){alert('as')}() // NaN ~function(){alert('as')}() // -1
void function(){alert('as')}() // undefined
new function(){alert('as')}() // Object
delete function(){alert('as')}() // true
(function(){alert('as')})() // undefined
(function(){alert('as')}()) // undefined
More Examples
Option | Code |
! | !function(){;}() |
+ | +function(){;}() |
- | -function(){;}() |
~ | ~function(){;}() |
-1 | (function(){;})() |
-2 | (function(){;}()) |
void | void function(){;}() |
new | new function(){;}() |
delete | delete function(){;}() |
= | var i = function(){;}() |
&& | 1 && function(){;}() |
|| | 0 || function(){;}() |
& | 1 & function(){;}() |
| | 1 | function(){;}() |
^ | 1 ^ function(){;}() |
, | 1, function(){;}() |
No comments:
Post a Comment