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);
Share
Improve this question
asked Feb 19, 2018 at 23:28
dev-ccdev-cc
4543 silver badges13 bronze badges
4
-
1
Which part don't you understand? Break it down:
2 + "2"
->"22"
; then-"22"
->-22
; then~-22
->21
. Does this existing Q&A answer your question? If not, could you edit to be more specific about what it is? – jonrsharpe Commented Feb 19, 2018 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 Commented Feb 19, 2018 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 Commented Feb 19, 2018 at 23:34
-
1
Check this out
https://www.joezimjs./javascript/great-mystery-of-the-tilde/
– MaveRick Commented Feb 19, 2018 at 23:37
2 Answers
Reset to default 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.
- 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 in21
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 pliment.
So:
- -22 representation is the 2's pliment of +22
- +22 in binary =
0000 0000 0000 0000 0000 0000 0001 0110
- 2's pliment of (22) = (-22) =
1111 1111 1111 1111 1111 1111 1110 1001
- 1 =
1111 1111 1111 1111 1111 1111 1110 1010
- 1 =
~-22
= bitwise not of -22 =0000 0000 0000 0000 0000 0000 0001 0101
10101
in binary =21
in decimal