Ship internal tools in hours, not weeks. Real auth, users, jobs, audit logs, and cohesive UI included. Early access $249 $499 → [Get it now]

How to find the maximum value in an array in JavaScript

Finding the maximum value in numeric arrays is essential for data analysis, creating charts, determining price ranges, and implementing features like progress bars or statistical displays in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I have implemented maximum value calculations in components like dashboard charts, pricing tables, and analytics widgets where identifying peak values is crucial for data visualization. From my extensive expertise, the most elegant and efficient solution is using Math.max() combined with the spread operator to find the largest number. This approach is concise, readable, and leverages JavaScript’s built-in mathematical functions for optimal performance.

Use Math.max() with the spread operator to find the largest value in an array.

const numbers = [3, 7, 2, 9, 1, 5]
const maximum = Math.max(...numbers)
// Result: 9

The Math.max() function finds the largest of the provided arguments, and the spread operator ... expands the array elements as individual arguments to the function. In this example, Math.max(...numbers) is equivalent to Math.max(3, 7, 2, 9, 1, 5), which returns 9 as the largest value. This method only works with numeric arrays and will return NaN if any element cannot be converted to a number. For empty arrays, it returns -Infinity.

Using Math.max() with the Spread Operator

The spread operator approach is the most common way to find the maximum value in modern JavaScript. It works well for small to medium-sized arrays.

const prices = [29.99, 49.99, 19.99, 99.99, 9.99]
const highestPrice = Math.max(...prices)
console.log(highestPrice) // 99.99

const temperatures = [-5, 12, 0, 8, -3, 15]
const hottest = Math.max(...temperatures)
console.log(hottest) // 15

// Works correctly with negative numbers and zero
const negatives = [-10, -3, -7, 0, -1]
const max = Math.max(...negatives)
console.log(max) // 0

Note that Math.max() handles negative numbers and zero correctly. The function compares all values numerically regardless of sign. Be aware that for empty arrays, Math.max() returns -Infinity, so always validate your input before calling this method.

Using reduce() for Large Arrays

For arrays larger than ~100,000 elements, the spread operator can cause a stack overflow because it passes every element as a separate function argument. The reduce() method processes elements one at a time and handles any array size safely.

const largeArray = Array.from({ length: 200_000 }, () =>
  Math.floor(Math.random() * 1_000_000)
)

const maximum = largeArray.reduce(
  (max, current) => (current > max ? current : max),
  -Infinity
)

console.log(maximum)

The reduce() approach iterates through each element and keeps track of the largest value found so far. The initial value is set to -Infinity so that any real number in the array will be larger. This pattern is also useful when you need to find the maximum and perform additional logic in the same pass, such as tracking the index of the maximum value.

const scores = [85, 92, 78, 95, 88]

const result = scores.reduce(
  (acc, current, index) => {
    if (current > acc.value) {
      return { value: current, index }
    }
    return acc
  },
  { value: -Infinity, index: -1 }
)

console.log(result) // { value: 95, index: 3 }

Finding the Maximum in an Array of Objects

Real-world data is often stored as arrays of objects. Use Math.max() with map() to extract the numeric property before comparing, as described in how to sort an array in JavaScript.

const products = [
  { name: 'Shirt', price: 29.99 },
  { name: 'Jacket', price: 89.99 },
  { name: 'Hat', price: 14.99 },
  { name: 'Shoes', price: 119.99 }
]

// Extract the maximum price
const maxPrice = Math.max(...products.map((p) => p.price))
console.log(maxPrice) // 119.99

// Get the entire object with the highest price
const mostExpensive = products.reduce((max, product) =>
  product.price > max.price ? product : max
)
console.log(mostExpensive) // { name: 'Shoes', price: 119.99 }

When you need the full object (not just the numeric value), reduce() is the better choice. It avoids a second lookup step and keeps the code efficient. This pattern is commonly used when building tables or lists that need to highlight the top-performing item, such as with the CoreUI Smart Table component.

Handling Mixed or Invalid Data

Arrays from external APIs or user input may contain non-numeric values. Never use .filter(Number) to clean them — it removes 0 because zero is falsy. Instead, filter explicitly with typeof or Number.isFinite().

const mixed = [10, 'hello', null, 42, undefined, 0, 7, NaN]

// Correct: keeps zeros, removes non-numbers
const safeMax = Math.max(
  ...mixed.filter((v) => typeof v === 'number' && Number.isFinite(v))
)
console.log(safeMax) // 42

// Wrong: .filter(Number) removes 0
const broken = Math.max(...mixed.filter(Number))
console.log(broken) // 42 (works here, but fails when 0 is the max)

const withZeroMax = [0, -5, -3, -1]
console.log(Math.max(...withZeroMax.filter(Number))) // -1 (wrong! should be 0)
console.log(
  Math.max(
    ...withZeroMax.filter((v) => typeof v === 'number' && Number.isFinite(v))
  )
) // 0 (correct)

Always validate data at the boundary where it enters your application. This is especially important when working with chart data in components like the CoreUI Chart where incorrect scale calculations can lead to misleading visualizations.

Finding the Maximum Date

The same techniques apply to Date objects by converting them to timestamps with getTime(). This approach is useful for scheduling features and timeline components.

const dates = [
  new Date('2026-01-15'),
  new Date('2026-03-22'),
  new Date('2026-02-08')
]

const latestTimestamp = Math.max(...dates.map((d) => d.getTime()))
const latestDate = new Date(latestTimestamp)

console.log(latestDate.toISOString()) // 2026-03-22T00:00:00.000Z

You can also find the minimum date using Math.min() with the same pattern. For more on finding minimum values, see how to find the minimum value in an array in JavaScript.

Using a Simple for Loop

A traditional for loop is the most performant approach and works in every JavaScript environment without any limitations.

function findMax(arr) {
  if (arr.length === 0) return undefined

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

const numbers = [3, 7, 2, 9, 1, 5]
console.log(findMax(numbers)) // 9
console.log(findMax([])) // undefined

This approach avoids the stack overflow risk of the spread operator and is slightly faster than reduce() because it has no function call overhead per element. Use it when performance is critical or when working with very large datasets. For related array operations like computing averages over the same data, see how to find the average of an array of numbers in JavaScript.

Best Practice Note:

For most use cases, Math.max(...array) is the best choice — it is concise, readable, and fast enough for arrays under 100k elements. Switch to reduce() or a for loop only when dealing with very large datasets. Always guard against empty arrays and non-numeric values at the boundary where data enters your application rather than inside utility functions.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team