Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the ~[] construction work in JavaScript?

I've come across a working JavaScript code that I can't explain. For example:

  • +[]===0
  • -[]===0
  • ~[]===-1
  • ~-~[]===-2
  • ~-~-~-~-~[]===-5
  • ~-~-~-~-~[]+~[]===-6
  • ~+~[]===0
  • ~+~+~[]===-1
  • ~+~+~+~[]===0

Can you explain the logic of these expressions?

like image 910
Denis Avatar asked Nov 23 '11 17:11

Denis


2 Answers

[] is an empty array object, so:

+[]: force empty array to be positive integer, aka 0, which is === to 0
-[]: force empty array to be negative integer, aka 0, which is === to 0
~[]: bitwise NOT empty array, which evaluates to -1, which is === to -1
~-~[]: bitwise NOT of negated NOTted empty array: ~-(-1) -> ~1 -> -2

etc...

like image 51
Marc B Avatar answered Oct 26 '22 08:10

Marc B


When you use the + or - operator on anything, it calls Number on it. Number([]) returns 0, so you get your first two answers.

The ~ operator is bitwise NOT. Basically it inverses all the bits in a number, which changes 0 to -1. More on bitwise operators here.

The rest are just combinations of those cases. You can pretty much combine those things to make any number you want.

like image 22
Alex Turpin Avatar answered Oct 26 '22 08:10

Alex Turpin