1

I saw this question in a test, but I don't understand how operators work on the statement.

let a = ~-(2 + "2");
console.log(a);
dev-cc
  • 434
  • 3
  • 13
  • 1
    Which part don't you understand? Break it down: `2 + "2"` -> `"22"`; then `-"22"` -> `-22`; then `~-22` -> `21`. Does [this existing Q&A](https://stackoverflow.com/q/12299665/3001761) answer your question? If not, could you [edit] to be more specific about what it is? – jonrsharpe Feb 19 '18 at 23:30
  • 1
    Did you try doing this a step at a time in the javascript console of your browser? Try `2 + "2"` first, and so on... – lurker Feb 19 '18 at 23:31
  • simple answer, because type coercion, maths and bitwise operations - all these are documented - try mdn documentation for up to date documentation – Jaromanda X Feb 19 '18 at 23:34
  • 1
    Check this out `https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/` – MaveRick Feb 19 '18 at 23:37

2 Answers2

10
~-(2 + "2")
  • 0: 2 + "2" (Concatenation) = "22"
  • 1: -"22" (Coercion) = -22
  • 2: ~-22 (Bitwise NOT) = -(-22 + 1) = 21

Bitwise NOTing any number x yields -(x + 1). For example, ~-5 yields 4.

Ele
  • 33,468
  • 7
  • 37
  • 75
  • According to your response ~-0xffffffff = -(-4294967295 + 1) = 4294967294. Sorry the result is -2 – tdjprog Feb 20 '18 at 00:59
  • @tdjprog So is it correct to say that all numbers under `2^32` will behave as described by this answer, and that those above that threshold will overflow in some way and behave differently? – IMSoP Jun 13 '18 at 17:05
2
  • Step 1: (2+"2") results in the string "22"
  • Step 2: -("22") is the same as (-1)*("22"), and results in the number -22
  • Step 3: Bitwise not (~), which results in 21

To understand that last step, you need to know that JavaScript stores numbers as 64-bit floating point numbers, but all bitwise operations are performed on 32-bit signed integers using 2's compliment.

So:

  • -22 representation is the 2's compliment of +22
  • +22 in binary = 0000 0000 0000 0000 0000 0000 0001 0110
  • 2's compliment of (22) = (-22) = 1111 1111 1111 1111 1111 1111 1110 1001
    • 1 = 1111 1111 1111 1111 1111 1111 1110 1010
  • ~-22 = bitwise not of -22 = 0000 0000 0000 0000 0000 0000 0001 0101
  • 10101 in binary = 21 in decimal
IMSoP
  • 89,526
  • 13
  • 117
  • 169
tdjprog
  • 706
  • 6
  • 11