Skip to content

Instantly share code, notes, and snippets.

@indexzero
Created July 29, 2011 21:39
Show Gist options
  • Save indexzero/1114798 to your computer and use it in GitHub Desktop.
Save indexzero/1114798 to your computer and use it in GitHub Desktop.
~ and ~~ in Arrays
var x = [1,2,3,4,5],
y = ['a', 'b', 'c', 'd', 'e'];
// console.log(x.indexOf(6)); // -1
// console.log(x.indexOf(5)); // 4
//
// if(x.indexOf(6) === - 1) { // if -1 === -1
// console.log(true, 'x.indexOf(6) === - 1');
// }
//
// if(x.indexOf(5) !== - 1) {
// console.log(true, 'x.indexOf(5) !== - 1');
// }
//
// if (~~x.indexOf(6)) { // -1, but still evaluates to true
// console.log(true, '~~x.indexOf(6)');
// }
//
// if (~~x.indexOf(5)) { // 4, but still evaluates to true
// console.log(true, '~~x.indexOf(5)');
// }
//
// if(x.indexOf(6)) { // -1, but still evaluates to true
// console.log(true, 'x.indexOf(6)');
// }
//
// if(x.indexOf(5)) { // 4, evaluates to true
// console.log(true, 'x.indexOf(5)');
// }
console.log('y.indexOf("e")', y.indexOf('e')); // 4
console.log('y.indexOf("f")', y.indexOf('f')); // -1
console.log('~y.indexOf("e")', ~y.indexOf('e'));
console.log('~y.indexOf("f")', ~y.indexOf('f'));
console.log('~~y.indexOf("e")', ~~y.indexOf('e'));
console.log('~~y.indexOf("f")', ~y.indexOf('f'));
if (y.indexOf('f') === - 1) { // if -1 === -1
console.log(true, 'y.indexOf("f") === - 1');
}
if (y.indexOf('f') !== - 1) { // if -1 === -1
console.log(true, 'y.indexOf("f") !== - 1');
}
if (~~y.indexOf('f')) { // -1, but still evaluates to true
console.log(true, '~~y.indexOf("f")');
}
if (y.indexOf('e') === - 1) {
console.log(true, 'y.indexOf("e") === - 1');
}
if (y.indexOf('e') !== - 1) {
console.log(true, 'y.indexOf("e") !== - 1');
}
if (~y.indexOf('e')) { // 4, but still evaluates to true
console.log(true, '~y.indexOf("e")');
}
if (~~y.indexOf('e')) {
console.log(true, '~~y.indexOf("e")');
}
if (!~y.indexOf('e')) {
console.log(true, '!~y.indexOf("e")');
}
@rafaelrinaldi
Copy link

Interesting!

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