Alex Rivera | Logout

How does the ~[] construction work in JavaScript?

Asked 2011-11-23T17:16:48.860
8

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?

Edit
Report

2 Answers

1

I'll do my best:

[]===0 is of course false because [] is not exactly equal to 0. However, []==0 is true because an implicit cast exists.

+ and -[] work because the plus or minus casts [] to a real number.

~0 (the bitwise inverse of 0) is -1. Thus ~[]===-1 works.

The others work just by subtracting or adding -1 a bunch of times.

answered 2011-11-23T17:27:18.767
0

I believe, correct me if I'm wrong, but adding to an array (as in, adding a value to an array rather than adding a value into an array) casts it to a number. The rest is just using basic +, - operators (the tilde (~) is a bitwise NOT) to modify the number and then an equation.

So [] == array ([]);
[] + 1 == number (0);
+[]===0 (true)
answered 2011-11-23T17:26:08.473

Your Answer