Skip to content
the poor coder

how to return the max and min of an array in javascript

Poor Man
Published
Reading time
2 min read
On this page

How to Return the Max and Min of an Array in JavaScript#

If you have an array of numbers in JavaScript and you want to find the maximum and minimum values, there are several ways to do it. Here are a few methods:

Method 1: Using Math.max() and Math.min()#

The simplest way is to use the built-in Math.max() and Math.min() functions in JavaScript. These functions take any number of arguments and return the maximum or minimum value.

Text

var numbers = [1, 2, 3, 4, 5];
var max = Math.max.apply(null, numbers);
var min = Math.min.apply(null, numbers);

In the above code, we first define an array of numbers. We then use the apply() method to call the Math.max() and Math.min() functions with the numbers array as arguments. The null argument is used to set the this value inside the called function to the global object.

Method 2: Using a For Loop#

We can also find the maximum and minimum values of an array using a for loop. Here's an example:

Text

var numbers = [1, 2, 3, 4, 5];
var max = -Infinity;
var min = Infinity;

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > max) {
    max = numbers[i];
  }
  if (numbers[i] < min) {
    min = numbers[i];
  }
}

In the above code, we first define an array of numbers. We then loop through each element of the array using a for loop. Inside the loop, we check if the current number is greater than the current maximum or less than the current minimum. If it is, we update the max or min variable.

Method 3: Using the Spread Operator#

Finally, we can use the spread operator (...) to pass the array elements as arguments to the Math.max() and Math.min() functions. Here's an example:

Text

var numbers = [1, 2, 3, 4, 5];
var max = Math.max(...numbers);
var min = Math.min(...numbers);

In the above code, we use the spread operator to pass each element of the numbers array as an argument to the Math.max() and Math.min() functions. This is equivalent to calling the functions with each element of the array as a separate argument.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC