Open In App

Spread vs Rest operator in JavaScript ES6

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 Operator

The rest operator is represented by three dots (…). When used in a function’s parameter list, it catches any extra arguments passed to the function and packs them neatly into an array. This allows functions to handle varying numbers of arguments without explicitly defining them. So, you can think of it as a way to gather up the remaining arguments into an array for easy handling inside the function.

Example: The rest operator gathers all arguments passed to the function after the first one (10 in this case) into an array called rest.

Javascript




function abc(a, ...rest) {
return rest;
}
console.log(abc(10, 1, 2, 3, 4, 5));


Output

[ 1, 2, 3, 4, 5 ]

Spread Operator

The spread operator, represented by three dots (…), works by taking all the items in an array and spreading them out, essentially unpacking the array so that each item becomes an individual element. It’s like taking a bunch of items from a box and laying them out separately on a table. This makes it easier to work with the individual items rather than dealing with the entire array as a single entity.

Example: This example shows the use of SPread Operator

Javascript




function abc(a, b, c) {
return a + b + c;
}
 
console.log(abc(...[1, 2, 3]));


Output

6

DIfference between Spread Operator and Rest Operator

Feature

Spread Operator

Rest Operator

Syntax

Denoted by three consecutive dots (…)

Denoted by three consecutive dots (…)

Usage

Used to expand an iterable into individual elements

Used in function parameters to gather arguments

Example

[…array]

function functionName(…args) { … }

Parameter Position

Can be used anywhere in an array literal or function call

Must be the last parameter in a function’s parameter list

Return Value

Creates a new array with copied elements

Note: See the above explanation

Gathers remaining arguments into an array

Note: See the above explanation

Mutability

Does not modify the original array or object

Note: See the above explanation

Gathers arguments into an array without altering them

Note: See the above explanation

Use Cases

Concatenating arrays, passing arrays as arguments

Capturing an arbitrary number of function arguments



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads