You’ve used it, you know it. Given a series of numbers, it returns you the biggest one. Simple. Easy. Definitely not blog post worthy.
Syntax
Math.max([value1[, value2[, ...]]])
Usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var x = Math.max(1, 2, 3); // 3 |
Thank You
That’s it for this week’s blog post, have a good day everyone…!
Spooky Stuff
Oh… You’re still here?
Huh? What happens if you pass some weird stuff to Math.max()? … oh, I mean… we could try some stuff:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This isn't spooky, this makes sense! | |
Math.max('apple'); // NaN | |
// One bad apple spoils the whole bunch... | |
Math.max(1, 2, 'apple'); // NaN | |
// but wait, JavaScript don't give a crap | |
// as long as it can implicitly convert stuff! | |
Math.max(1, 2, '3'); // 3 | |
// but wait, maybe it *does* care...? If it is | |
// in an array?? | |
Math.max([1, '2', 3]); // NaN | |
// Spread operator to the rescue! Now it works |
|
Math.max(...[1, '2', 3]); // 3 | |
// F**K... | |
Math.max(...[]); // -Infinity | |
// Ok seriously just stop | |
Math.max([]); // 0 | |
// WHAT | |
Math.max(); // -Infinity | |
// I'm going to go home | |
Math.max(null); // 0 | |
// Goodbye, cruel world | |
Math.max(undefined); // NaN |
I was going to try and explain why this happens, but, I just can’t. I have no idea. So I’m just going to let this serve as a reminder that JavaScript is pretty wild.