What do these characters do in javascript

I was looking at the code snippet http://cssdeck.com/labs/bjiau4dy and I saw this in a Javascript block -

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

What does it do? and why it does not lead to errors in the console?

Thank!

+5
source share
3 answers

Any of these characters turns the function that follows it into an expression of the function instead of declaring the function. Putting them all together is just for fun.


If you try to call a regular function, putting ()immediately after the declaration:

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

you will get a syntax error:

Syntax Error: Unexpected token (

since you cannot call a function declaration.


, , :

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

, :

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

. : http://kangax.github.com/nfe/#expr-vs-decl

+4

, .

, .

JS 1 +1 () !1 (false) ! +1 ( false). , .

, !+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!1 . false, .

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

, - , . +function(){ ... } .

0

, , . + number, -. ! not boolean (true/false).

, , - , Javascript - . "" "" , "" ( , AKA NaN).

, JSFiddle Firebug , , , - .

:

  • !function(){} false ( true).
  • +function(){} NaN ( NaN). , -.
  • !+function(){} true ( NaN false, false true.
  • !+-+-+!function(){} true ( !function(){} false, +false 0 + -, , , !0 true).
  • Using the operators, as they are listed in your example, will go back and forth between false, -1, 0, 1 true, until all the operators are evaluated.

Please note that I tested them with Firebug. There may be differences between browsers and, perhaps, what Firebug shows us when evaluating. TL DR is that Javascript does many types of coercion and will evaluate expressions differently than declarations.

0
source

All Articles