site icon

Hi, I’m Chris

I am a web developer teaching
regular people how to code

~ Welcome to my blog ~

Javascript Numbers: How to Easily Find the Largest or Smallest Values

Have multiple numbers in Javascript and want to find the largest/smallest? This post will show you how to easily do this!

All we need to do is take advantage of some built in Javascript Math methods called min() and max().

Let's begin with finding the largest number value:

const highest = Math.max(1, 77, 34);

console.log(highest); // 77

Here we use the max() method, pass in some values, and the highest value is stored as a constant.

You can now probably guess how min() works now too:

const lowest = Math.min(1, 77, 34);

console.log(lowest); // 1

Both of these methods can also be used with negative numbers too.

What about arrays of numbers? The first thought may be to create an array, and pass it into min/max():

const numbers = [1, 77, 34];

const highest = Math.max(numbers);
console.log(highest); // NaN

This will result in NaN because we are passing in an array, rather than the actual numbers contained in it.

To extract the values from the array, we can use the Javascript spread syntax:

const numbers = [1, 77, 34];

const highest = Math.max(...numbers);
console.log(highest); // 77

And again this can also be used with min() too, resulting in the lowest number.

- By Chris Dixon

Chris Dixon is a web developer and teacher. Teaching thousands of students mainly in Vue.js React.js, WordPress and web development.