Get the Max of two Numbers using JavaScript

avatar

Borislav Hadzhiev

Sun Oct 31 20212 min read

Get the Max of two Numbers in JavaScript #

Use the Math.max() function to get the max of 2 numbers, e.g. Math.max(10, 5). The function returns the largest of the provided numbers. If any of the provided parameters is not a number and can't be converted to one, NaN is returned.

index.js
console.log(Math.max(5, 10)); // ๐Ÿ‘‰๏ธ 10 console.log(Math.max(0, 20)); // ๐Ÿ‘‰๏ธ 20 console.log(Math.max(-10, 10)); // ๐Ÿ‘‰๏ธ 10 console.log(Math.max(-10, -15)); // ๐Ÿ‘‰๏ธ -10 console.log(Math.max('5', '15')); // ๐Ÿ‘‰๏ธ 15 console.log(Math.max('zero', 'five')); // ๐Ÿ‘‰๏ธ NaN

We used the Math.max function to get the max of two numbers.

The function takes zero or more numbers as parameters and returns the largest number. This means you could provide more than 2 numbers to the function.

index.js
console.log(Math.max(1, 3, 5, 7)); // ๐Ÿ‘‰๏ธ 7
If any of the provided values is not of type number, the function attempts to convert it to a number before making the comparison.

If the function fails to convert the value to a number, it returns NaN (not a number).

Note that there are some non numeric values that get converted to a valid number in JavaScript. Here are some examples.

index.js
console.log(Number([])); // ๐Ÿ‘‰๏ธ 0 console.log(Number(null)); // ๐Ÿ‘‰๏ธ 0 console.log(Number(false)); // ๐Ÿ‘‰๏ธ 0 console.log(Number(true)); // ๐Ÿ‘‰๏ธ 1 console.log(Number('')); // ๐Ÿ‘‰๏ธ 0

If you pass any of these values to the Math.max() function, you might get confusing results.

index.js
console.log(Math.max(null, -10)); // ๐Ÿ‘‰๏ธ 0 console.log(Math.max([], -10)); // ๐Ÿ‘‰๏ธ 0 console.log(Math.max(true, -10)); // ๐Ÿ‘‰๏ธ 1
In these examples the Math.max function converted the first value to a number before comparing the values. Since all of these convert successfully to a number, we got some unexpected results.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee