Skip to content

Instantly share code, notes, and snippets.

@selfish
Last active November 5, 2015 17:54
Show Gist options
  • Save selfish/7c0911779ce465e0e118 to your computer and use it in GitHub Desktop.
Save selfish/7c0911779ce465e0e118 to your computer and use it in GitHub Desktop.
Bitwise Operations Make life easier in JS:
function isOdd(number) {
return !!(number & 1);
}
isOdd(1); // true, 1 is odd
isOdd(2); // false, 2 is not odd
isOdd(357); // true, 357 is odd
// In JavaScript, you can use a double bitwise negation (~~n) as a replacement for Math.floor(n) (if n is a positive number) or parseInt(n, 10) (even if n is negative). n|n and n&n always yield the same results as ~~n.
var n = Math.PI;
n; // 3.141592653589793
Math.floor(n); // 3
parseInt(n, 10); // 3
~~n; // 3
n|n; // 3
n&n; // 3
// ~~n works as a replacement for parseInt() with negative numbers…
~~(-n); // -3
(-n)|(-n); // -3
(-n)&(-n); // -3
parseInt(-n, 10); // -3
// …although it doesn’t replace Math.floor() for negative numbers
Math.floor(-n); // -4
//A single bitwise negation (~) calculates:
-(parseInt(n, 10) + 1);
// So two bitwise negations will return:
-(-(parseInt(n, 10) + 1) + 1);
//It should be noted that of these three alternatives, n|n appears to be the fastest.
(3 | 0) === 3; // Integers not alter
(3.3 | 0) === 3; // With fractional numbers truncate
(3.8 | 0) === 3; // Not round, namely truncate
(-3.3 | 0) === -3; // Including negative and fractional numbers
(-3.8 | 0) === -3; // Who Math.floor (-3.3) == Math.floor (-3.8) == -4
("3" | 0) === 3; // Line with the numbers are converted to integers
("3.8" | 0) === 3; // This again truncate
("-3.8" | 0) === -3; // Including negative and fractional numbers
(NaN | 0) === 0; // NaN is reduced to zero
(Infinity | 0) === 0; // Zeroing occurs with infinity
(-Infinity | 0) === 0; // And minus infinity,
(null | 0) === 0; // And null,
((void 0) | 0) === 0; // And undefined,
([] | 0) === 0; // And empty arrays
([3] | 0) === 3; // But an array with a single number is given to the number,
([-3.8] | 0) === -3; // Including discarding the fractional part,
(["-3.8"] | 0) === -3; // And including removing the number of rows
([-3.8, 22] | 0) === 0; // but an array with a few numbers again vanishes
({} | 0) === 0; // To zero also contains an empty object
({2 '' '3'} | 0) === 0; // Or not empty
((Function () {}) | 0) === 0; // To zero also contains the empty function
((Function () {return 3;}) | 0) === 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment