Program to find largest of three numbers - JavaScript


We are required to write a JavaScript function that takes in three or more numbers and returns the largest of those numbers.

For example: If the input numbers are −

4, 6, 7, 2, 3

Then the output should be −

7

Example

Let’s write the code for this function −

// using spread operator to cater any number of elements
const findGreatest = (...nums) => {
   let max = -Infinity;
   for(let i = 0; i < nums.length; i++){
      if(nums[i] > max){
         max = nums[i];
      };
   };
   return max;
};
console.log(findGreatest(5, 6, 3, 5, 7, 5));

Output

The output in the console −

7

Updated on: 15-Sep-2020

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements