Find The Maximum Value Of An Array In JavaScript

Use the following function to find the maximum value of an array of numbers in JavaScript.

function findMaximum(array) {
  let max = array[0];
  for (let i = 1; i < array.length; i++) {
    if (array[i] > max) {
      max = array[i];
    }
  }
  return max;
}

Alternatively, you can also use the unpack operator to unpack the array and use the Math.max() function to return the maximum value.

function findMaximum(array) {
  return Math.max(...array);
}

You can run this function like this:

let array = [3,40,20,1,10];
console.log(findMaximum(array)); // Prints "40".

See this code in action in a CodePen.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
6 + 13 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.