Sub topic 3
Finding Extremes and Magnitudes: min, max, abs, and sign
This chapter assumes you can run JavaScript in Node.js or a browser console, and that you already know how NaN, Infinity, and the safe integer range behave.
min, max, abs, and sign
Math.max and Math.min take separate arguments, so you spread an array into them. If you call them with no arguments, they return the identity values -Infinity and Infinity. If any argument is NaN, the result is NaN.
console.log(Math.max(3, 7, 2)); // 7
console.log(Math.min(...[3, 7, 2])); // 2
console.log(Math.max()); // -Infinity
console.log(Math.max(1, NaN)); // NaN
console.log(Math.abs(-5)); // 5
console.log(Math.sign(-5)); // -1Powers, Roots, and Logarithms
console.log(2 ** 10); // 1024
console.log(Math.sqrt(-1)); // NaN
console.log(Math.cbrt(27)); // 3
console.log(Math.hypot(3, 4)); // 5
console.log(Math.log2(8)); // 3
console.log(-7 % 3); // -1 (keeps the dividend's sign)
console.log(((-7 % 3) + 3) % 3); // 2 (true modulo)Random Integers in a Range
Math.random() returns a float in [0, 1). To get an integer in a range, scale the float and then floor it:
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6));
const bytes = new Uint32Array(1);
crypto.getRandomValues(bytes); // use this for tokens and keys
console.log(bytes[0]);Math.random is not cryptographically secure. Never use it for passwords, session IDs, or keys.
Trigonometry and Math.atan2
The trigonometric functions take radians. Math.atan2(y, x) returns the correct angle in all four quadrants.
console.log(Math.sin(90 * Math.PI / 180)); // 1
console.log(Math.atan2(1, 1) * 180 / Math.PI); // 45Bitwise Operators and 32-Bit Conversion
Bitwise operators convert their operands to 32-bit signed integers first. That conversion drops fractions and wraps large values around:
console.log(-7.9 | 0); // -7
console.log(2 ** 31 | 0); // -2147483648BigInt Beyond the Safe Range
console.log(9007199254740992 === 9007199254740993); // true
console.log(2n ** 64n); // 18446744073709551616n
console.log(10n / 3n); // 3n
try { 1n + 1; } catch (e) { console.log(e instanceof TypeError); } // trueYou can't mix BigInt and Number in arithmetic. Convert one side explicitly first, for example 1n + BigInt(1).
Exercise
Why does Math.floor(Math.random() * 6) + 1 never return 7, and why is x | 0 a bad way to truncate 3000000000?
Show answer
Math.random() is always below 1, so the product is below 6 and the floor is at most 5, which gives at most 6. The | 0 operation converts to a 32-bit signed integer, so 3000000000 wraps to -1294967296. Use Math.trunc instead.