Look at the following code:
let max = Math.max(1, 2, 3, 4, 5);
As you can see, this code contains the maximum of the numbers. But what if our numbers are represented as an array? For example, like this:
let arr = [1, 2, 3, 4, 5];
Unfortunately, we cannot do the following:
let arr = [1, 2, 3, 4, 5];
let max = Math.max(arr); // you can't pass an array here
Of course, we can manually put the array
elements into Math.max
, like this:
let arr = [1, 2, 3, 4, 5];
let max = Math.max(arr[0], arr[1], arr[2], arr[3], arr[4]);
However, in this case, any universality
is lost: our code will only find the maximum
value for an array of 5
elements.
What if we need more or less elements in the array? There is a solution! We use the spread operator:
let arr = [1, 2, 3, 4, 5]
let max = Math.max(...arr);
This code, despite its simplicity, is very
powerful. After all, Math.max
can
take any number of parameters, which means
that using the spread operator, we can use
an array of arbitrary size!
Given an array of numbers. Using
Math.min
and spread, display
the minimum value of the array.