Skip to content

Instantly share code, notes, and snippets.

@paulosborne
Created November 25, 2013 12:40
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paulosborne/7640679 to your computer and use it in GitHub Desktop.
Save paulosborne/7640679 to your computer and use it in GitHub Desktop.
Hipster indexOf
var message = "hello, how are you Tal?";
if (~message.indexOf('Tal')) {
console.log('found matching text');
}
@purefan
Copy link

purefan commented Nov 25, 2013

is this equivalent to?

if (!!message.indexOf('Tal')) {
    console.log('found matching text');
}

@ken210
Copy link

ken210 commented Nov 25, 2013

Nope

message.indexOf('Tal'); // 19
~message.indexOf('Tal'); // 20

message.indexOf('non-matching string'); // -1
~message.indexOf('non-matching string'); // 0

!!message.indexOf('non-matching string'); // true
!!~message.indexOf('non-matching string'); // false

@cluebcke
Copy link

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 means false, 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.

function tilde(count) {
    console.time('tilde');
    for (var i = 0; i < count; i++) ~i;
    console.timeEnd('tilde');
}

function greaterThanNegativeOne(count) {
    console.time('greaterThanNegativeOne');
    for (var i = 0; i < count; i++) i > -1;
    console.timeEnd('greaterThanNegativeOne');
}   

var count = process.argv[2];
tilde(count);
greaterThanNegativeOne(count);

Results

$ node tildeVsGreaterThan.js 100000000
tilde: 8437ms
greaterThanNegativeOne: 8438ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment