Hiprup

What is the spread operator for function arguments?

The spread operator expands an array into individual arguments when calling a function.

  • Replaces apply — fn(...args) is the modern alternative to fn.apply(null, args).

  • Combine — mix spread with regular arguments freely.

  • Math example — Math.max(...numbers) finds the max of an array.

Cleaner and more readable than apply for passing an array as separate arguments.

const numbers = [5, 2, 8, 1, 9];

// Before spread (apply)
console.log(Math.max.apply(null, numbers)); // 9

// With spread (cleaner)
console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 1

// Multiple spreads
const arr1 = [1, 2];
const arr2 = [3, 4];
console.log([...arr1, ...arr2]);   // [1, 2, 3, 4]

function sum(a, b, c) { return a + b + c; }
console.log(sum(...[1, 2, 3]));     // 6

// With new (apply cannot do this)
const args = [2024, 0, 15];
const date = new Date(...args);     // Jan 15, 2024
// new Date.apply(null, args) — TypeError!

...numbers expands the array into individual arguments: Math.max(5, 2, 8, 1, 9). Replaces the verbose .apply(null, array) pattern. Works with new (apply cannot).

Multiple arrays can be spread in one call. Sum example shows spreading into a regular function.

Spread replaces .apply for passing arrays as arguments. Math.max(...arr) is the classic example.

Works with new (apply cannot). Cleaner and more readable than the .apply pattern.

What is the spread operator for function arguments? | Hiprup