We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. Learn More
contact@techquestworld.com
+919547614783
Premium Article
Published 4 months ago

Find Maximum and Minimum in an Array in JavaScript

5 min read
405 views
Find Maximum and Minimum in an Array in JavaScript
Photo by Techquestworld

Discover different ways to find the maximum and minimum values in a JavaScript array. Perfect for beginners, interview prep and real-world projects.

🔹 Using Math.max() and Math.min() with Spread Operator

This is the most straightforward method using built-in JavaScript functions.

const numbers = [34, 12, 78, 5, 99];

const max = Math.max(...numbers);
const min = Math.min(...numbers);

console.log("Max:", max); // 99
console.log("Min:", min); // 5

🔹 Using reduce() Method

Perfect when you want a functional approach.

const numbers = [34, 12, 78, 5, 99];

const max = numbers.reduce((acc, val) => acc > val ? acc : val);
const min = numbers.reduce((acc, val) => acc < val ? acc : val);

console.log("Max:", max); // 99
console.log("Min:", min); // 5

🔹 Using a Loop (for beginners)

A traditional way to find max and min manually.

const numbers = [34, 12, 78, 5, 99];

let max = numbers[0];
let min = numbers[0];

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

console.log("Max:", max); // 99
console.log("Min:", min); // 5

🔹 Handling Empty Arrays

Always handle edge cases before running operations.

function getMaxMin(arr) {
if (arr.length === 0) return { max: null, min: null };

return {
max: Math.max(...arr),
min: Math.min(...arr)
};
}

console.log(getMaxMin([])); // { max: null, min: null }

Finding max and min in an array is a basic but powerful skill in JavaScript. From quick one-liners to custom logic, now you have multiple tools to get the job done. Pick the one that fits your use case and code smartly.

📺 Subscribe to our YouTube Channel for practical dev content:

👉 @theroxycoder

Author
TAPAS SAHOO

Developer by Profession, Techie by Heart

A curious mind with a love for writing and technology, dedicated to simplifying web development and programming topics while keeping up with the ever-changing tech landscape.

Discussion (0)

Replying to
Previous Article
ExpressJS vs NestJS: Which Node.js Framework...

Discover the core differences between ExpressJS and NestJS. Whether you build APIs or full-scale app...

Next Article
Build Your Own Code Snippet Manager with Reac...

Make your own React-based Code Snippet Manager app — save, tag and search reusable code blocks easil...

Related Articles