JavaScript Code

How to find largest element in array?


Problem Statement

given an array of numbers, write a JavaScript program to find the largest element in the array

Solution

to find the largest element in an array, we iterate over each of the element in array, and compare it with the assumed largest number. if the assumed largest number is less than the element during an iteration, we update the largest number with the element. at the end of the looping statement, we get the largest number in the array

we use for loop for iteration, and comparison greater than operator to compare values in an if statement

Program

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

let nums = [4, 7, 0, 1, 12, -1, 5];
let largest = -Infinity;
for ( let index = 0; index < nums.length; index++ ) {
    if ( nums[index] > largest ) {
        largest = nums[index];
    }
}
console.log(largest);

we initialised largest with the smallest number possible, and updated it with the element if largest is smaller than the element



copyright @2022