JavaScript Code

How to find smallest element in array?


Problem Statement

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

given array of numbers nums, and find the smallest number in nums

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



copyright @2022