Curriculum Series

Spread operator in JavaScript

Spread operator in JavaScript

Spread operator in JavaScript

JavaScript

The short answer

The spread operator (...) expands an iterable (like an array or object) into individual elements. It lets you copy arrays, merge objects, pass array elements as function arguments, and more — all with a clean, short syntax.

Spreading arrays

The most common use is copying and merging arrays:

JAVASCRIPT
1// Copying an array
2const original = [1, 2, 3];
3const copy = [...original]; // [1, 2, 3]
4
5// Merging arrays
6const first = [1, 2];
7const second = [3, 4];
8const merged = [...first, ...second]; // [1, 2, 3, 4]
9
10// Adding elements
11const numbers = [2, 3, 4];
12const withExtra = [1, ...numbers, 5]; // [1, 2, 3, 4, 5]

Spreading objects

You can also spread objects to copy or merge them:

JAVASCRIPT
1// Copying an object
2const user = { name: 'John', age: 30 };
3const copy = { ...user }; // { name: "John", age: 30 }
4
5// Merging objects
6const defaults = { theme: 'light', lang: 'en' };
7const userPrefs = { theme: 'dark' };
8const settings = { ...defaults, ...userPrefs };
9// { theme: "dark", lang: "en" }

When you spread multiple objects and they have the same key, the last one wins. In the example above, theme from userPrefs overrides theme from defaults.

Function arguments

You can spread an array into function arguments:

JAVASCRIPT
1const numbers = [5, 2, 8, 1, 9];
2
3Math.max(...numbers); // 9
4// same as Math.max(5, 2, 8, 1, 9)

Before the spread operator, you had to use apply:

JAVASCRIPT
1Math.max.apply(null, numbers); // the old way

In React

Spread is used everywhere in React:

JAVASCRIPT
1// Spreading props
2const buttonProps = { type: 'submit', disabled: true };
3<button {...buttonProps}>Submit</button>;
4
5// Updating state immutably
6const [user, setUser] = useState({ name: 'John', age: 30 });
7setUser({ ...user, age: 31 });

Common Pitfalls

Remember that spread only creates a shallow copy. If your object has nested objects, the inner objects are still references to the original. Changing a nested property on the copy will also change the original. If you need a deep copy, use structuredClone.

Interview Tip

Show that you know the difference between spread for arrays and objects, and mention that it creates a shallow copy. If the interview is React-focused, show how spread is used for immutable state updates — this is something you will do in almost every React app.

Why interviewers ask this

The spread operator is used constantly in modern JavaScript and React. Interviewers want to see if you know the common use cases, if you understand it creates a shallow copy (not a deep copy), and if you can use it to write clean, readable code.

Finished reading?

Mark this topic as solved to track your progress.