← Back to libraryQuestion 153 of 468
🧩JavaScript CodingBeginner

Find the Largest Number in an Array

📌 Definition:

Return the maximum value in an array of numbers.

📖 Detailed Explanation:

Use Math.max with spread for small arrays, or a single reduce/loop for very large arrays (spread can hit argument-count limits on huge arrays).

💻 Solutions:
const max = (arr) => Math.max(...arr);

// Safe for very large arrays:
function maxSafe(arr) {
  let m = -Infinity;
  for (const n of arr) if (n > m) m = n;
  return m;
}
🔑 Key Points:
  • Math.max(...arr) is concise but spreads all elements as arguments
  • Very large arrays can exceed the argument limit — use a loop/reduce
  • Start the accumulator at -Infinity
  • O(n) time
🌍 Real-World Example:

Finding a max/min is a building block for stats dashboards and for validating that a test dataset's values fall in range.

🎯 Scenario-Based Interview Question:

Math.max(...bigArray) throws 'Maximum call stack size exceeded' for a 200k-element array. Why, and what's the fix?