Spread in function calls
Learn to spread an array's elements as function arguments.
Spread in calls
Spread also works in a function call. Writing Math.max(...scores) passes every element of the scores array as a separate argument; it is the same as Math.max(85, 92, 78).
This is handy with Math.max, Math.min or any multi-parameter function you write. Instead of passing the array as one argument, you expand its elements.
The old way: apply
Before spread, passing an array as arguments meant using apply: Math.max.apply(null, scores). It works, but it is hard to read; passing null is a trick to ignore the this binding.
Modern code prefers Math.max(...scores). It gives the same result, is shorter, and shows the intent clearly. When you see apply in old code, know it can now be replaced with spread.
Exercise Compute the invoice with spread
Write a function called calculateTotal(price, tax, discount). In its body, return price + tax - discount. Create an array called invoice (for example [100, 18, 10]). Use spread to pass the elements of invoice as arguments to calculateTotal and log the result with console.log.
Show example solution
function calculateTotal(price, tax, discount) {
return price + tax - discount;
}
const invoice = [100, 18, 10];
console.log(calculateTotal(...invoice));
Test yourself
-
What does `Math.max(...nums)` do?
const nums = [85, 92, 78]; const top = Math.max(...nums);- It passes the `nums` array itself as a single argument
- It passes each element of `nums` as a separate argument
- It passes the value of `nums.length`
- It sorts the `nums` array alphabetically
Show answer
It passes each element of `nums` as a separate argument — Correct. Spread expands the array; each element becomes its own argument.
-
Match the call styles
- Math.max(...nums)
- Find the largest value
- fn.apply(null, arr)
- Old way
- ...arr (in a call)
- Expand array into arguments
-
Find the highest score
const scores = [85, 92, 78]; const highest = Math.max(____); console.log(highest);Show answer
const scores = [85, 92, 78]; const highest = Math.max(...scores); console.log(highest);