JavaScript Exercises Basic#5 - Finding the smallest number from array

JavaScript Exercises Basic#5 - Finding the smallest number from array

You will be given few numbers in an array. Write a program which finds the smallest one among the numbers.

Solution

         function solution(arr){
                //Declare a variable 'min'. 'Min' is supposed to store the smallest number but I'll just assume the first number of array is the smallest one.
                let min = arr[0]

                //While iterating the array, compare the elements with 'min'. If the element is smaller than 'min', update the value
                for (let i = 0; i < arr.length; i++){
                    if (arr[i] < min) min = arr[i];
                }

                return min;
            }

Easier Solution

function solution(arr){
                //Math.min() will return the lowest-valued number passed into it. 
                //It will return NaN if any parameter isn't a number, so we should use the spread operator to change an array into numbers
                let min = Math.min(...arr);
                return min;
            }

Result

Screenshot 2022-04-12 at 22.13.50.png