Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange anonymous javascript function call [duplicate]

Tags:

javascript

I was looking at this very cool snippet and i came across this weird line in the js and deleting that prevent the function from being invoked

!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!
function(d, w){
   ...
}(document, window);

,i wrapped the function with ( ) as it supposed to be and it works as intended.

(function(d, w){
    ...
})(document, window);

so my question is what is that weird line and why does it work? my wild guest is that it is some kind IIFE...

like image 731
MimiEAM Avatar asked Apr 23 '13 13:04

MimiEAM


2 Answers

And you are right, it is an Immediately-Invoked Function Expression (IIFE)

You can rewrite

!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!
function(d, w){
   ...
}(document, window);

to

!function() {
    ...
}()

and it still works. This is because ! is a unary operator (just like +, -, and ~ -- see https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators). After an unary operator an expression is expected (and evaluated!). The expression can be a function call.

However

!function() {
    ...
}()

is just another expression, so you can put another unary operator in front of it:

+!function() {
    ...
}()

You can continue this pattern as you wish.

Note: Invoking an anonymous function this way, ignores the return value of the function. So only use this, if you are not interested in the return value.

Edit: Added an excellent reference to http://benalman.com/news/2010/11/immediately-invoked-function-expression/ which Daff mentioned in his answer.

like image 178
tessi Avatar answered Nov 02 '22 23:11

tessi


The trick is actually the single ! operator there (the entire first line actually does the same thing). This will work just as well:

!function(d, w){
   ...
}(document, window);

As always I can recommend Ben Almans great article on Immediately-Invoked Function Expressions

like image 27
Daff Avatar answered Nov 02 '22 23:11

Daff