mdev mdev - 6 months ago 20
Javascript Question

What does Math.random() * i | 0 mean?

var lst = [/*List of items*/];
for (var i = 10; i > 0; i--) {
lst.appendChild(lst[Math.random() * i | 0]);
}


Why would "|" be in a index? Does this function shuffle the list 'lst'?

Answer

The bitwise OR operator | converts its input to a 32-bit two-complement number. This is often used for fast rounding towards zero (faster than Math.trunc()).

console.log(1.1 | 0); // 1
console.log(1.9 | 0); // 1
console.log(-1.1 | 0); // -1
console.log(-1.9 | 0); // -1

PS: A double bitwise negation ~~ has the same effect. Keep in mind that applying bitwise operators effectively reduces the range of integer operands from Number.MAX_SAFE_INTEGER (2⁵³ - 1) to the maximum 32-bit two-complement (2³¹ - 1).