Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Spread vs Rest operator in JavaScript ES6
Next article icon

JavaScript Spread Operator

Last Updated : 11 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Spread operator (represented as three dots or …) is used on iterables like array and string, or properties of Objects. to expand wherever zero or more elements are required top be copied or assigned. Its primary use case is with arrays, especially when expecting multiple values. The syntax of the Spread operator is the same as the Rest parameter but it works opposite of it.

1. Adding Multiple Elements Using Spread Operator

Even though we get the content on one array inside the other one, actually it is an array inside another array which is definitely what we didn’t want. If we want the content to be inside a single array we can make use of the spread operator. 

javascript
// expand using spread operator  let a = [10, 20]; let b = [...a, 30, 40];  console.log(a);  

Output
[ 10, 20 ] 

We can insert at the beginning and both begin and end together also

JavaScript
// expand using spread operator  let a = [10, 20]; let b = [30, 40, ...a, 50, 60];  console.log(a);  

Output
[ 10, 20 ] 

2. Find Min / Max using Spread Operator

Math object method won’t work and will return NaN. When …arr is used in the function call, it “expands” an iterable object arr into the list of arguments In order to avoid this NaN output, we make use of a spread operator. we make use of a spread operator In order to avoid this NaN

javascript
// Min in an array using Math.min() let a = [1,2,3,-1]; console.log(Math.min(a)); //NaN  // Now using spread  console.log(Math.min(...a));  

Output
NaN -1 

3. Passing Array Elements as Function Parameters

JavaScript
function add(x, y, z) {   return x + y + z; }  let a = [10, 20, 30]; console.log(add(...a)); 

Output
60 

4. Copying Array using Spread

We are copying all the elements of the given array to the another new array by the use of the spread operator.

JavaScript
const a = [1, 2, 3]; const b = [...a];  console.log(b);   // Please note that in JavaScript, doing // b = a does not create a clone. It only creates // one more reference. You may try uncommening the // below code //  const c = [1, 2, 3]; //  const d = c; //  d.push(4); //  console.log(c); // Prints [1, 2, 3, 4] 

Output
[ 1, 2, 3 ] 

Please refer Clone an array for different methods of copying an array in JS

5. Concatenate Arrays using Spread Operator

The spread operator can be used to concatenate more than one array.

javascript
// Spread operator for array concatenation let a = [1, 2, 3]; let b = [4, 5];  a = [...a, ...b]; console.log(a); 

Output
[ 1, 2, 3, 4, 5 ] 

Note: Though we can achieve the same result as the concat method, it is not recommended to use the spread in this particular case, as for a large data set it will work slower when compared to the native concat() method.

6. Working of Objects with Spread Operator

ES6 has added spread property to object literals in javascript. The spread operator (…) with objects is used to create copies of existing objects with new or updated values or to make a copy of an object with more properties. Let’s take an example of how to use the spread operator on an object, 

javascript
const usr = {     name: 'Jen',     age: 22 };  const cloneUsr = { ...usr }; console.log(cloneUsr); 

Output
{ name: 'Jen', age: 22 } 

Here we are spreading the usr object. All key-value pairs of the usr object are copied into the cloneUsr object.

Let’s look at another example of merging two objects using the spread operator.

javascript
const usr1 = {     name: 'Jen',     age: 22, };  const usr2 = {     name: "Andrew",     location: "Philadelphia" };  const mergedUsers = { ...usr1, ...usr2 }; console.log(mergedUsers); 

Output
{ name: 'Andrew', age: 22, location: 'Philadelphia' } 

The mergedUsers is a copy of usr1 and usr2. Actually, every enumerable property on the objects will be copied to the mergedUsers object. The spread operator is just a shorthand for the Object.assign() method but, there are some differences between the two.

Below is an example of adding properties to an object using spread operator.

JavaScript
const o1 = { a: 1, b: 2 }; const o2 = { ...o1, b: 3, c: 4 }; console.log(o2);  

Output
{ a: 1, b: 3, c: 4 } 

We have a complete list of Javascript Operators, to check those please go through the Javascript Operators Complete Reference article.



Next Article
Spread vs Rest operator in JavaScript ES6

Y

YugShah
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-operators

Similar Reads

  • Operator precedence in JavaScript
    Operator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution. ( * ) and ( / )
    2 min read
  • Spread vs Rest operator in JavaScript ES6
    Rest and spread operators may appear similar in notation, but they serve distinct purposes in JavaScript, which can sometimes lead to confusion. Let's delve into their differences and how each is used. Rest and spread operators are both introduced in javascript ES6. Rest OperatorThe rest operator is
    2 min read
  • ES6 Spread Operator
    Spread Operator is a very simple and powerful feature introduced in the ES6 standard of JavaScript, which helps us to write nicer and shorter code. The JavaScript spread operator is denoted by three dots (...). The spread operator helps the iterable objects to expand into individual elements. Iterab
    3 min read
  • JavaScript Assignment Operators
    Assignment operators are used to assign values to variables in JavaScript. [GFGTABS] JavaScript // Lets take some variables x = 10 y = 20 x = y // Here, x is equal to 20 console.log(x); console.log(y); [/GFGTABS]Output20 20 More Assignment OperatorsThere are so many assignment operators as shown in
    6 min read
  • JavaScript Arithmetic Operators
    JavaScript Arithmetic Operators are the operator that operate upon the numerical values and return a numerical value. Addition (+) OperatorThe addition operator takes two numerical operands and gives their numerical sum. It also concatenates two strings or numbers. [GFGTABS] JavaScript // Number + N
    6 min read
  • Rest Parameter And Spread Operator in JavaScript
    JavaScript introduced the Rest Parameter and Spread Operator in ES6 to make handling functions and arrays more flexible and concise. These operators use the same syntax (...), but they serve different purposes. The rest parameter collects multiple values into an array, while the spread operator spre
    6 min read
  • JavaScript Spread Syntax (...)
    The spread syntax is used for expanding an iterable in places where many arguments or elements are expected. It also allows us the privilege to obtain a list of parameters from an array. The spread syntax was introduced in ES6 JavaScript. The spread syntax lists the properties of an object in an obj
    4 min read
  • JavaScript Operators Coding Practice Problems
    Operators in JavaScript allow you to perform operations on variables and values, including arithmetic, logical, bitwise, comparison, and assignment operations. Mastering JavaScript operators is essential for writing efficient expressions and conditional statements. This curated list of JavaScript op
    1 min read
  • How Spread Operator Works in JS
    The spread operator (...) in JavaScript is a powerful feature used to expand or spread elements of an iterable (like an array or object) into individual elements. It is commonly used in situations where you want to copy or merge arrays, objects, or even pass arguments to functions. 1. Arrays with th
    3 min read
  • Right Shift (>>) Bitwise Operator in JavaScript
    JavaScript bitwise right shift operator is used to operate on two operands where the left operand is the number and the right operand specifies the number of bits to shift towards the right. A copy of old leftmost bits is maintained and they have added again the shifting is performed. The sign bit i
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences