← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 1 of 12

JS Spread Operator

What Is Spread Syntax

The spread operator ... expands an iterable like an array or a string into its individual elements wherever multiple values are expected, such as inside an array literal or a function call.

Example: What Is Spread Syntax

javascript
const nums = [1, 2, 3];
console.log(...nums); // expands array into individual values
console.log([...nums]);

Combining Arrays

Spreading two or more arrays into a new array literal, like [...a, ...b], concatenates their elements into a single new array without mutating either original array, and lets you insert extra values anywhere in the mix.

Example: Combining Arrays

javascript
const a = [1, 2];
const b = [3, 4];
const combined = [...a, ...b, 5];
console.log(combined);

Copying Objects

Spreading an object with {...obj} copies its own enumerable properties into a new object, a common pattern for creating an updated copy without touching the original, often combined with new properties to override specific fields.

Example: Copying Objects

javascript
const obj = { name: "Sam", age: 30 };
const copy = { ...obj, age: 31 };
console.log(copy);

Spread with Function Calls

Spread works inside function calls too, turning an array like [1, 2, 3] into three separate arguments, so Math.max(...numbers) passes each number individually instead of the array itself.

Example: Spread with Function Calls

javascript
const numbers = [1, 5, 3];
console.log(Math.max(...numbers));

Shallow Copy Limitation

Spread only copies one level deep, so nested objects or arrays inside the spread value are copied by reference, meaning changes to a nested object still affect both the original and the copy.

Example: Shallow Copy Limitation

javascript
const original = { info: { city: "Delhi" } };
const copy = { ...original };
copy.info.city = "Mumbai";
console.log(original.info.city); // "Mumbai" - nested object is shared

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.