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
JavaScript Arrays
JavaScript Array Methods
JavaScript Objects
Exercises & Assignments
Write a JavaScript program to find the sum and average of array elements
Write a JavaScript program to find the largest and smallest number in an array
Write a JavaScript program to remove duplicates from an array
Write a JavaScript program to filter even numbers and double them
Write a JavaScript program to count the frequency of words in a sentence
Interview Questions & Answers
What is the difference between map and forEach?
What is the difference between slice and splice?
What is the difference between shallow copy and deep copy in JavaScript?
What is the difference between spread and rest operators?
What are Map and Set in JavaScript?
How do you check if a variable is an array in JavaScript?