Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Spread Operator in Functions

The spread operator (...) expands arrays or iterables into function arguments.

It makes function calls with array data clean and readable.

Why We Need It

Without spread, you need apply or manual indexing to pass arrays as arguments.

Spread makes your intent clear and your code concise.

Syntax

fn(...iterable)

Basic Example

1. Spread into function

const nums = [3, 7, 2];
console.log(Math.max(...nums));

Spread turns array items into separate arguments.

Real World Example

2. Merge 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.

Multiple Use Cases

Expand Arrays

Spread expands an array into individual arguments.

It makes calling functions with array data concise.

Combine with Rest

Spread and rest look the same but do opposite jobs.

Spread expands; rest collects.

Practical Uses

Use spread with Math functions, copy arrays, and pass dynamic arguments.

It improves readability over apply or manual loops.

More Examples

3. Clone arrays

const original = [1, 2];
const copy = [...original, 3];

console.log(copy);

Spread is a clean way to clone and extend arrays.

4. With rest

function logAll(...items) {
  console.log(items);
}

const values = ["a", "b"];
logAll(...values);

Spread and rest work well together.

Comparison

Without

const nums = [1, 2, 3];
console.log(Math.max.apply(null, nums));

With

const nums = [1, 2, 3];
console.log(Math.max(...nums));

Common Mistakes and Fixes

Confusing rest and spread

Rest collects, spread expands.

Spreading non-iterables

Spread only works on iterables like arrays and strings.

Overusing spread in hot loops

Be mindful of performance in tight loops.

Interview Questions

What does spread do in function calls?

It expands an iterable into separate arguments.

Rest vs spread?

Rest collects into an array; spread expands from an array.

Can you spread strings?

Yes, strings are iterable and spread into characters.

Practice Problem

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));

Frequently Asked Questions

What does spread do?

It expands an iterable into individual elements.

How is it different from rest?

Rest collects arguments, spread expands them.

Can I spread objects into function args?

No, objects are not iterable unless you use Object.values().

Try It Yourself

Try spreading different arrays into Math.max.