javascript program to find largest of 2 numbers

A program to find the largest of 2 numbers in javascript.

Program to find the largest of 2 numbers in javascript

const largest = (a, b) => a > b ? a : b;

console.log(largest(10, 20));
//20

Find the largest number from a given array.

An array contains different values and to find the find the largest number from it, we will have to iterate each element and then keep track of the largest one.

const largest = (arr) => {
  let max = Number.MIN_SAFE_INTEGER;
  for(let val of arr){
    if(val > max){
      max = val;
    }
  }
  return val;
}

console.log(largest([10, 20, 30, 40, 50]));
//50

Using Math.max to find the largest element from the array.

Math.max takes numbers as arguments and returns the max number.

Using the … spread operator we can pass all the elements of the array as parameter to the Math.max method and it will then return the max out of them.

const arr = [10, 20, 30, 40, 50];
cont max = Math.max(...arr);

console.log(max);
//50