Reputation: 14208
Every so often I run across someone using (!~val)
instead of (val === -1)
in situations where -1 is returned from a function (e.g. indexOf()
).
To me, the logical NOT + bitwise NOT statement seems horribly unreadable when compared to the -1 comparison. Is there enough of a speed difference to warrant using one over the other? Or if not speed, some other reason that I'm missing to use a bitwise NOT instead of === ?
(Aplologies in advance if this is a dup., but I couldn't find an answer to this exact question. Searching for "!~" doesn't quite work in SO or Google)
Upvotes: 3
Views: 101
Reputation: 160181
Is it a meaningful performance difference? Likely not, but it depends entirely on the VM.
You can always find out using something like http://jsperf.com/
Upvotes: 1
Reputation: 105019
Both are f@$# off fast.
If your script has performance issues it definitely won't boil down to this boolean check. But as others have stated these two are not (completely) the same.
Upvotes: 0
Reputation: 9619
No, they are definitely not the same.
The bitwise conversion will do an implicit type coercion. The === operator checks for type equality.
So these these two can give completely different results.
var val = "-1";
(!~val) // true
(val === -1) // false
In a situation like this I think the intent and correctness of the comparison far outweighs any performance consideration. Decide what exactly you want to compare and use the right comparison for the job.
Upvotes: 3