What is the difference in both approach. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the difference in both approach.

1st approach let arr = [1,2,3,4,5,6]; let max = arr.reduce(function (a,b){ return Math.max(a,b); }); console.log(max); //6 And 2nd approach, console.log(Math.max(...arr)); //6 Both return the same value but I want to know when and why we use each of them? Thanks in advance

5th Mar 2020, 2:41 PM
Neeraj Swarnkar
Neeraj Swarnkar - avatar
1 Answer
+ 1
The first one is just a convoluted way to find the max. Usually you want to choose the simple straightforward way to solve a problem. If you can just take max, take it. Reduce applies a function on two values, leaving only one, and goes on with it, until all values 'melded' into one. You can define any sort of complicated algorithm for this, and could achieve all sort of goals. For finding a max - overkill.
5th Mar 2020, 3:50 PM
HonFu
HonFu - avatar