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:
What is spread, default and rest parameters in JavaScript ?
Next article icon

Rest Parameter And Spread Operator in JavaScript

Last Updated : 19 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 spreads elements from an array or object.

Rest parameter

The Rest Parameter allows functions to accept an indefinite number of arguments as an array. It collects multiple arguments into a single array parameter.

JavaScript
// Rest Parameter function myFunc(...args) {     console.log(args); } myFunc(1, 2, 3, 4, 5); 

Output
[ 1, 2, 3, 4, 5 ] 
  • The ...args in myFunc(...args) collects all passed arguments into an array called args.
  • When calling myFunc(1, 2, 3, 4, 5), it prints [1, 2, 3, 4, 5] because all arguments are grouped into args.

Using Rest Parameter in Functions

The rest parameter allows a function to accept an indefinite number of arguments as an array.

JavaScript
function sum(...numbers) {     return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1,2,3,4,5)) 

Output
15 
  • The sum function uses the rest parameter to gather arguments. It calculates the sum of all passed numbers.
  • ...numbers gathers all arguments into an array.
  • The reduce method iterates over the array and sums the values.
  • The default value of 0 ensures the sum starts correctly.
  • numbers would become an array after passing of arguments to the sum function and it will look like [1,2,3,4,5].

Use cases of rest parameter

1. Collecting Function Arguments

The rest parameter collects names into an array. The function greets all the names.

JavaScript
function greet(greeting, ...names) {     return `${greeting}, ${names.join(' and ')}`; } console.log(greet("Pranjal", "Tanamaya", "Sonam")); 

Output
Pranjal, Tanamaya and Sonam 
  • ...names gathers remaining arguments.
  • The join method creates a string combining names.
  • The result is a personalized greeting.

2. Filtering Properties in Objects

Destructuring extracts property a. The rest parameter gathers remaining properties.

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

Output
1 { b: 2, c: 3 } 
  • a is assigned 1.
  • ...rest collects { b: 2, c: 3 }.
  • This separates key-value pairs.

3. Destructuring with Rest

Destructuring extracts the first element. The rest parameter gathers remaining elements.

JavaScript
const [first, ...rest] = [1, 2, 3, 4]; console.log(first) console.log(rest) 

Output
1 [ 2, 3, 4 ] 
  • first receives the value 1.
  • ...rest collects [2, 3, 4].
  • Both variables are distinct.

4. Function Default Parameters

The rest parameter collects numbers. The function multiplies each by a given factor.

JavaScript
function mul(factor, ...nums) {     return nums.map(num => num * factor); } console.log(mul(2,1,2,3,4,5)) 

Output
[ 2, 4, 6, 8, 10 ] 
  • ...numbers gathers extra arguments into an array.
  • map applies the multiplication to each element.
  • The result is a new array of products.

Spread operator

The spread operator (...arr) in JavaScript is used to expand an array or object into individual elements. It allows you to easily pass elements from an array as separate arguments in a function call or combine multiple arrays into one. The spread operator helps to make code more concise and readable when working with arrays or objects.

JavaScript
const n = [1, 2, 3]; const ne = [...n, 4, 5];   console.log(ne);  

Output
[ 1, 2, 3, 4, 5 ] 
  • The ...n spread operator expands the n array into individual elements, so [...n, 4, 5] becomes [1, 2, 3, 4, 5].
  • The code then logs the new array ne, which contains the original elements plus 4 and 5 at the end.

Expanding Arrays

The spread operator which is denoted by ... allows iterable elements (like arrays or objects) to expand into individual elements.

JavaScript
const a1 = [1, 2, 3]; const a2 = [...a1, 4, 5]; console.log(a2) 

Output
[ 1, 2, 3, 4, 5 ] 
  • The spread operator expands a1 into individual elements. These elements are combined with additional values into a2.
  • ...a1 expands [1, 2, 3] into 1, 2, 3.
  • These elements are placed into a2 alongside 4 and 5.
  • The resulting array is [1, 2, 3, 4, 5].

Use cases of spread operator

1. Merging Arrays

Arrays a1 and a2 are merged using the spread operator. The result is a single combined array.

JavaScript
const a1 = [1, 2]; const a2 = [3, 4]; const merged = [...a1, ...a2]; console.log(merged) 

Output
[ 1, 2, 3, 4 ] 
  • ...a1 and ...a2 expand the arrays.
  • Elements from both arrays are combined in order.
  • The result is [1, 2, 3, 4].
  • The final result will be stored in the merged variable.

2. Cloning Arrays

The spread operator creates a shallow copy of the original array. The new array, clone, is independent of the original.

JavaScript
const original = [10, 20, 30]; const clone = [...original]; console.log(clone) 

Output
[ 10, 20, 30 ] 
  • ...original expands elements into a new array.
  • Changes to clone won't affect original.
  • Both arrays share the same initial data.

3. Combining Objects

Objects obj1 and obj2 are combined using the spread operator. Properties in obj2 override those in obj1.

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

Output
{ a: 1, b: 3, c: 4 } 
  • ...obj1 and ....obj2 expand properties into a new object.
  • Duplicate keys are overridden by later objects.
  • The result is { a: 1, b: 3, c: 4 }.
  • In this case b is present as a key in both the objects but the second b overwrites the value of first one.

4. Merging Arrays

Arrays array1 and array2 are merged using the spread operator. The result is a single combined array.

JavaScript
const a1 = [1, 2]; const a2 = [3, 4]; const merged = [...a1, ...a2]; console.log(merged) 

Output
[ 1, 2, 3, 4 ] 
  • ...a1 and ...a2 expand the arrays.
  • Elements from both arrays are combined in order.
  • The result is [1, 2, 3, 4].
  • The final result will be stored in the merged variable.

5. Combining Objects

Objects obj1 and obj2 are combined using the spread operator. Properties in obj2 override those in obj1.

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

Output
{ a: 1, b: 3, c: 4 } 
  • ...obj1 and ....obj2 expand properties into a new object.
  • Duplicate keys are overridden by later objects.
  • The result is { a: 1, b: 3, c: 4 }.
  • In this case b is present as a key in both the objects but the second b overwrites the value of first one.

Key Features-spread operator and rest parameter

  • Simplifies handling of variable-length data.
  • Works seamlessly with arrays and objects.
  • Supports function argument flexibility.
  • Enables concise syntax for common operations.
  • Enhances code readability and maintainability.

Advantages-spread operator and rest parameter

  • Reduces boilerplate code for data manipulation.
  • Provides clear and expressive syntax.
  • Ensures immutability in operations like cloning.
  • Supports both functional and object-oriented paradigms.
  • Widely supported across modern JavaScript environments.

Differences Between Rest Parameter and Spread Operator

FeatureRest ParameterSpread Operator

Syntax

function(...args) {}

[...array], {...object}

PurposeCollects multiple arguments into an arrayExpands elements of an array, object, or string
UsageFunction parametersArrays, objects, function calls
ReturnsAn arrayIndividual elements

Conclusion

Both the Rest Parameter and Spread Operator are powerful features in JavaScript that enhance the flexibility of handling arrays and objects. The rest parameter is useful for gathering multiple function arguments, while the spread operator is great for expanding arrays, merging objects, and passing arguments efficiently.


Next Article
What is spread, default and rest parameters in JavaScript ?
author
isitapol2002
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-operators
  • JavaScript-Questions

Similar Reads

  • 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
  • What is spread, default and rest parameters in JavaScript ?
    The default, spread, and rest parameters were added in ES6. Default Parameter: It is used to give the default values to the arguments, if no parameter is provided in the function call. Syntax: function fnName(param1 = defaultValue1, ..., paramN = defaultValueN) { ... } Example 1: In the below exampl
    2 min read
  • 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
  • JavaScript Spread Operator
    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
    4 min read
  • What does OR Operator || in a Statement in JavaScript ?
    JavaScript is a dynamic programming language that allows developers to write complex code with ease. One of the fundamental concepts in JavaScript is the use of operators, which are symbols that perform operations on one or more values. One such operator is the || (logical OR) operator, which can be
    6 min read
  • JavaScript Rest parameter
    The JavaScript Rest parameter allows a function to accept an indefinite number of arguments as an array. It is represented by three dots (...) followed by the parameter name and must be the last parameter in the function, enabling flexible and dynamic argument handling. Syntax//... is the rest param
    4 min read
  • Right Shift Assignment(>>=) Operator in JavaScript
    The Right Shift Assignment Operator is represented by ">>=". This operator shifts the first operand to the right and assigns the result to the variable. It can also be explained as shifting the first operand to the right in a specified amount of bits which is the second operand integer and the
    1 min read
  • JavaScript Operators Reference
    JavaScript Operators are used to perform specific mathematical and logical computations on operands. In other words, an operator operates the operands. In JavaScript, operators are used to compare values, perform arithmetic operations, etc. Example: In this example, we will use typeof operator to ch
    5 min read
  • JavaScript Unsigned Right Shift Assignment Operator
    In JavaScript ">>>=" is known as the unsigned right shift assignment bitwise operator. This operator is used to move a particular amount of bits to the right and returns a number that is assigned to a variable. Syntax: a >>>= b Meaning: a = a >>> b Return value: It returns
    1 min read
  • Remainder Assignment(%=) Operator in Javascript
    The Remainder Assignment Operator in javascript is represented by "%=". This operator is used to divide the value of the variable by another operand and assign the remainder to the variable which is the first operand. This can be also explained as assigning the remainder to the first operand which i
    1 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