Other than a slight performance gain, is there an advantage to using !~x as true vs. checking to see if ~-1 ?
Asked
Active
Viewed 142 times
0
-
2`if (~someString.indexOf(someOtherString)){...}` is nice, but not always clear. – Shmiddty May 31 '13 at 20:37
-
`~1` is `-2`, `~~X` can be used to do a 'floor' on `X` (where X is positive) – Shmiddty May 31 '13 at 20:43
-
1What do you mean by _"checking to see if ~-1"_? Is your question `~x` vs `x != -1`? – Eric May 31 '13 at 20:48
2 Answers
3
There can be a difference for large numbers. Because you're confined to a 32-bit range, consider the following.
var x = Math.pow(2,32)-1; // 4294967295
console.log(~x); // 0
So here you get a 0
result giving you the opposite boolean conversion than you'd expect.
-
2Still not sure if this answers the question, because I'm not sure what the question actually is. :( – Shmiddty May 31 '13 at 20:52
-
@Shmiddty: I'm pretty sure your comment under the question describes what the asker is getting at. But if this is an Array or Array-like collection that can have very high indices, there can be an unexpected results. – May 31 '13 at 20:56
-
1
0
There's no behavioral difference. Use whichever is clearest for the scenario you're implementing.

Chris Tavares
- 29,165
- 4
- 46
- 63