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);
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);
~-(2 + "2")
2 + "2"
(Concatenation) = "22"
-"22"
(Coercion) = -22
~-22
(Bitwise NOT) = -(-22 + 1) = 21 Bitwise NOTing any number x yields -(x + 1). For example, ~-5 yields 4.
(2+"2")
results in the string "22"
-("22")
is the same as (-1)*("22"), and results in the number -22
~
), 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:
0000 0000 0000 0000 0000 0000 0001 0110
1111 1111 1111 1111 1111 1111 1110 1001
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