Write a JavaScript program to find the largest and smallest number in an array

Description: Find the largest and smallest number in [45, 12, 89, 3, 67].

Hint:

  • Math.max takes separate numbers, so spread the array with ....

JavaScript largest and smallest in an array

const numbers = [45, 12, 89, 3, 67];

console.log("Largest:", Math.max(...numbers));
console.log("Smallest:", Math.min(...numbers));

// with a loop
let max = numbers[0];
let min = numbers[0];
for (const n of numbers) {
  if (n > max) max = n;
  if (n < min) min = n;
}
console.log(max, min);

Output:

Tutorials Class - Output Window

Largest: 89
Smallest: 3
89 3

How it works

  • ...numbers spreads the array into separate arguments.
  • The loop keeps the biggest and smallest value seen so far.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.