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?
[]
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With