Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do these characters do in Javascript [duplicate]

I was going through a piece of code here http://cssdeck.com/labs/bjiau4dy and I saw this in the Javascript box -

!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!

What does that do ? and why does it not throw errors in the console ?

Thanks!

like image 425
user1437328 Avatar asked Oct 05 '22 04:10

user1437328


1 Answers

Any of those symbols turn the function that follows it into a function expression, instead of a function declaration. Putting them all in there together is just for fun.


If you try to call a regular function by putting () right after the declaration:

function () {
    // this is a syntax error...
}();

you'll get a syntax error:

SyntaxError: Unexpected token (

since you cannot call a function declaration.


So people usually wrap an anonymous function in parentheses to turn it into a function expression:

(function () {
    // this will execute immediately
}());

You can achieve the same thing be prepending any of those symbols:

!function () {
    // this will also execute immediately
}();

For more information, see here: http://kangax.github.com/nfe/#expr-vs-decl

like image 185
Joseph Silber Avatar answered Oct 10 '22 03:10

Joseph Silber