javascript

Get the largest value from an array using javascript

In this post, we will learn different methods and functions to get the largest value from an array. We will use Math.max() function in order to do that along with other methods with explanation.

Get the largest value from an array using javascript

To get the largest value from an array:

  1. Create an array eg. - arr = [50, 20, 60, 90, 30, 70].
  2. Use Math.max() function to get the largest value from the array. eg. Math.max(...arr).

Using Math.max() function

The Math.max() function in JavaScript is used to return the largest value from a given array of numbers. It takes an array of numbers as an argument and returns the number with the highest value in the array.
It is a built-in function used to find the largest number in the array. It is a very useful and convenient tool for quickly determining the largest value from an array of numbers. This function can be used to quickly and easily find the maximum value for a given array of numbers.
We will also use the spread operator in Math.max() function.

Syntax

Math.max(...array)
const arr = [50, 20, 60, 90, 30, 70];

const max_val = Math.max(...arr);

console.log(max_val);

Output

90

This code snippet declares a constant array and assigns it some values. It then declares a constant called max_val and assigns it the value of the highest number in the array using the Math.max() method with the spread operator. Finally, it prints the value of max_val to the console.


Using for loop

function largest_val(arr) {
    let max = arr[0];
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

const max_val = largest_val([50, 20, 60, 90, 30, 70]);

console.log(max_val);

Output

90
Was this helpful?