Skip to content

Instantly share code, notes, and snippets.

@reergymerej
Last active August 29, 2015 13:56
Show Gist options
  • Save reergymerej/9284488 to your computer and use it in GitHub Desktop.
Save reergymerej/9284488 to your computer and use it in GitHub Desktop.
bitwise not vs. traditional indexOf
for (var i = 5; i >= -5; i--) {
console.log('~' + i + ' === '
+ ~i + ' == ' + (~i ? true : false));
}
// ~5 === -6 == true
// ~4 === -5 == true
// ~3 === -4 == true
// ~2 === -3 == true
// ~1 === -2 == true
// ~0 === -1 == true
// ~-1 === 0 == false
// ~-2 === 1 == true
// ~-3 === 2 == true
// ~-4 === 3 == true
// ~-5 === 4 == true
var str = 'teamwork';
// the standard way
if (str.indexOf('i') > -1) {
console.log('i here');
}
// the tricky way
if (~str.indexOf('i')) {
console.log('i here');
}
console.log((str.indexOf('i') > -1) === true);
console.log((~str.indexOf('i')) === true);
console.log((str.indexOf('a') > -1) === true);
console.log((~str.indexOf('a')) === true);
// false
// false
// true
// false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment