Expand Arrays
Spread expands an array into individual arguments.
It makes calling functions with array data concise.
JavaScript Tutorial
The spread operator (...) expands arrays or iterables into function arguments.
It makes function calls with array data clean and readable.
Without spread, you need apply or manual indexing to pass arrays as arguments.
Spread makes your intent clear and your code concise.
fn(...iterable)const nums = [3, 7, 2];
console.log(Math.max(...nums));Spread turns array items into separate arguments.
function sum(a, b, c) {
return a + b + c;
}
const parts = [1, 2, 3];
console.log(sum(...parts));Pass an array as parameters using spread.
Spread expands an array into individual arguments.
It makes calling functions with array data concise.
Spread and rest look the same but do opposite jobs.
Spread expands; rest collects.
Use spread with Math functions, copy arrays, and pass dynamic arguments.
It improves readability over apply or manual loops.
Without
const nums = [1, 2, 3];
console.log(Math.max.apply(null, nums));With
const nums = [1, 2, 3];
console.log(Math.max(...nums));Rest collects, spread expands.
Spread only works on iterables like arrays and strings.
Be mindful of performance in tight loops.
It expands an iterable into separate arguments.
Rest collects into an array; spread expands from an array.
Yes, strings are iterable and spread into characters.
Practice: Use spread to pass an array of three numbers into a function that multiplies them.
function multiply(a, b, c) {
return a * b * c;
}
const values = [2, 3, 4];
// TODO: call multiply with spread
One Possible Solution
function multiply(a, b, c) {
return a * b * c;
}
const values = [2, 3, 4];
console.log(multiply(...values));It expands an iterable into individual elements.
Rest collects arguments, spread expands them.
No, objects are not iterable unless you use Object.values().
Try spreading different arrays into Math.max.