How to find maximum value in an array using spread operator in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

We have logical methods and also many inbuilt methods to find a maximum value in an array, but the use of spread operator has made our task much easier to find the maximum value. Inbuilt method Math.max() is the most common method used to find a maximum value in an array. But in this method, we need to pass all the elements individually, making our task harder. So to alleviate this problem spread operator comes into the picture.

Example

In the following example, the spread operator doesn't accompany Math.max() function. Every value of an array is sent into the math function. It is fine if there is a small set of values, but in case of a large set of values, it is difficult to pass every element into math function. 

Live Demo

<html>
<body>
<script>
   var array = [1,2,3];
   var Max1 = Math.max(array);
   var Max2 = Math.max(array[1],array[1],array[2]) ;
   document.write(Max1);
   document.write("<br>");
   document.write(Max2);
</script>
</body>
</html>

Output

NaN
3


In the following example, spread operator (...) is used instead of sending each value into math function. This is a modern method used to find the maximum value in an array.

Example

Live Demo

<html>
<body>
<script>
   var array = [1,2,3];
   var Max1 = Math.max(array);
   var Max2 = Math.max(...array) ;
   document.write(Max1);
   document.write("<br>");
   document.write(Max2);
</script>
</body>
</html>

Output

NaN
3
raja
Published on 03-Jul-2019 11:14:00
Advertisements