Skip to content

Instantly share code, notes, and snippets.

@dillonforrest
Last active December 24, 2015 16:29
Show Gist options
  • Save dillonforrest/6827931 to your computer and use it in GitHub Desktop.
Save dillonforrest/6827931 to your computer and use it in GitHub Desktop.
Using the super-rare tilde operator in javascript

I just came across this interesting bit of javascript, which I've paraphrased:

var _ = require('underscore');
var coll = require('./some/external/array');

function contains(str, key) {
  return ~str.indexOf(key);
}

var filtered = _.filter(coll, contains);

The cool thing is the ~. Apparently, when the '~' operator is used with integers other than -1, it evaluates to false. Otherwise, if the tilde is used with -1, it evaluates to true. MAGIC.

EDIT: I misspoke. The ~ will evaluate -1 to 0, which is falsy, and will evaluate all other integers to something other than 0, which all will be truthy. :)

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