Spread Operator

qwerty_Sudhar_5333270798's avatar
Published Jan 8, 2025
Contribute to Docs

The Spread Operator in JavaScript, represented by three dots (...), is used to expand or unpack elements of arrays, objects, or other iterables into individual elements.

The spread operator performs a shallow copy, meaning that for nested objects or arrays, changes in the copied object/array might reflect in the original.

Syntax

The syntax of spread operator for arrays is as follows:

const nums = [...nums1 , ...nums2]   // arrays

The syntax of spread operator for objects is as follows:

const obj = {...obj1, ...obj2}      // objects
  • nums1 and nums2 are arrays. They represent any two arrays that need to be merged into a single array.
  • obj1 and obj2 are objects. They represent two objects that should be combined into one.

Example

The following example demonstrates how to use the spread operator:

const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
const nums = [...nums1, ...nums2];
console.log(nums);
const obj1 = { name: 'Subro' };
const obj2 = { age: 22 };
const obj = { ...obj1, ...obj2 };
console.log(obj);

This example results in the following output:

[1, 2, 3, 4, 5, 6]
{ name: 'Subro', age: 22 }

Codebyte Example

Run the codebyte example below to understand how the spread operator works:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy