JavaScript Code


How to find largest element in array in JavaScript?


Find largest element in Array in JavaScript

In this tutorial, you are 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

In the following program, we are given an array of numbers in nums. We shall 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