How to Find the Largest and Smallest Number in an Array Using JavaScript?

Estimated read time 2 min read

To find both the largest and smallest numbers in an array using JavaScript, you can use the Math.max() and Math.min() methods and spread operator ...:

var numbers = [1, 2, 3, 4, 5];
var largest = Math.max(...numbers);
var smallest = Math.min(...numbers);

console.log(largest); // Output: 5
console.log(smallest); // Output: 1

In this example, Math.max() and Math.min() are called with the spread operator ... to spread the elements of the numbers array into separate arguments. The result of the Math.max() call is the largest number in the numbers array, and the result of the Math.min() call is the smallest number in the numbers array.

Alternatively, you can loop through the array and keep track of both the largest and smallest numbers so far:

var numbers = [1, 2, 3, 4, 5];
var largest = Number.NEGATIVE_INFINITY;
var smallest = Number.POSITIVE_INFINITY;

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > largest) {
    largest = numbers[i];
  }
  if (numbers[i] < smallest) {
    smallest = numbers[i];
  }
}

console.log(largest); // Output: 5
console.log(smallest); // Output: 1

In this example, largest and smallest are variables that keep track of the largest and smallest numbers found so far. The for loop iterates through each element in the numbers array, and the if statements check whether the current element is greater than the largest number found so far and whether the current element is smaller than the smallest number found so far, and update largest and smallest respectively if either is true.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply