Get the Max of two Numbers using JavaScript


Borislav Hadzhiev

Last updated: Oct 31, 2021


Check out my new book

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.

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.

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.

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.

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 #

Use the search field on my Home Page to filter through my more than 3,000 articles.