Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  112] [ 7]  / answers: 1 / hits: 21103  / 13 Years ago, fri, april 29, 2011, 12:00:00

I've been seeing this syntax on a few libraries now and I'm wondering what the benefit is. (note i'm well aware of closures and what the code is doing, I'm only concerned about the syntactical differences)



!function(){
// do stuff
}();


As an alternative to the more common



(function(){
// do stuff
})();


for self invoking anonymous functions.



I'm wondering a few things. First off, what is allowing the top example to actually work? Why is the bang necessary in order to make this statement syntactically correct? I'm told also that + works, and I'm sure some others, in place of !



Second, what is the benefit? All I can tell is that it saves a single character, but I can't imagine that's such a huge benefit to attract numerous adopters. Is there some other benefit Im missing?



The only other difference I can see would be the return value of the self invoking function, but in both of these examples, we don't really care about the return value of the function since it's used only to create a closure. So can someone tell me why one might use the first syntax?


More From » syntax

 Answers
9

Ideally you should be able to do all this simply as:



function(){
// do stuff
}();


That means declare anonymous function and execute it. But that will not work due to specifics of JS grammar.



So shortest form of achieving this is to use some expression e.g. UnaryExpression (and so CallExpression):



!function(){
// do stuff
}();


Or for the fun:



-function(){
// do stuff
}();


Or:



+function(){
// do stuff
}();


Or even:



~function(){
// do stuff
return 0;
}( );

[#92493] Wednesday, April 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emerymariamm

Total Points: 276
Total Questions: 97
Total Answers: 99

Location: Comoros
Member since Sun, Dec 13, 2020
4 Years ago
;