JS Spread Operator
In this page:
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
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
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
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
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
const original = { info: { city: "Delhi" } };
const copy = { ...original };
copy.info.city = "Mumbai";
console.log(original.info.city); // "Mumbai" - nested object is shared
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: