JavaScript traps · JavaScript

JavaScript: Math.max() = -Infinity?!PRO

With nothing to compare, max starts from the smallest possible value. An empty list hits the same trap.

// Math.max() = -Infinity ?!
// With nothing to compare, max starts from the smallest possible value, so any real number wins.
console.log(Math.max());   // -Infinity ?!
console.log(Math.min());   // Infinity ?!

const scores = [];
console.log(Math.max(...scores));                       // -Infinity: an empty list hits the same trap
console.log(scores.length ? Math.max(...scores) : 0);   // 0 ✓ check for empty first
Open code JS9 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code JS9 in Code Library.