Created
November 25, 2013 12:40
-
-
Save paulosborne/7640679 to your computer and use it in GitHub Desktop.
Hipster indexOf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var message = "hello, how are you Tal?"; | |
if (~message.indexOf('Tal')) { | |
console.log('found matching text'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since I don't feel this has really been explained--
~
is the bitwise NOT operator in JS.~-1
is 0, and~anythingBesidesNegativeOne
is something other than 0. 0 is falsey, and all other numbers are truthy. Therefore, in those very few cases where-1
really meansfalse
, you can use the tilde operator to turn -1 into 0, and any other number into something besides 0.I wouldn't advise using this technique, though, at least not with code that many others will need to understand, maintain or enhance. It's quite obscure and a quick-and-dirty test (in Node) suggests that the difference in performance between using
~x
vs 'x > -1` is so small as to be nonexistent.Results