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)
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.
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.