Spread Operator
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
andnums2
are arrays. They represent any two arrays that need to be merged into a single array.obj1
andobj2
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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours