Find smallest element in Array in JavaScript
In this tutorial, you are given an array of numbers. Write a JavaScript program to find the smallest element in the array.
Solution
To find the smallest element in an array, we iterate over each of the element in array, and compare it with the assumed smallest number. If the assumed smallest number is greater than the element during an iteration, we update the smallest number with that element. At the end of the looping statement, we get the smallest number in the array.
We use for loop for iteration, and comparison less than operator to compare values in an if statement.
Program
In the following program, we are given an array of numbers in nums
. We shall find the smallest number in nums
using a for loop.
let nums = [4, 7, 0, 1, 12, -3, 5];
let smallest = Infinity;
for ( let index = 0; index < nums.length; index++ ) {
if ( nums[index] < smallest ) {
smallest = nums[index];
}
}
console.log(smallest);
We initialised smallest
with the largest number possible Infinity
, and updated it with the element if smallest
is larger than the element.