DEV Community

Cover image for JavaScript uses three dots (...) for both the rest and spread operators. But these two operators are not the same.
Tanvir Ahmed
Tanvir Ahmed

Posted on • Edited on

JavaScript uses three dots (...) for both the rest and spread operators. But these two operators are not the same.

Spread Operator:

The spread operator is used to break apart items in things like arrays, strings, or objects into individual pieces. It's often used to copy or join arrays, or to pass the items in an array as separate arguments to a function.

# 1.0 Array

1.1 Copy an array:
Instead of modifying the original array, you can create a shallow copy of an array.Image description

1.2 Concatenating arrays:
Using the spread operator, you can concatenate arrays easily without using .concat().
Image description

1.3 Adding elements to an array:
You can easily add new elements to an array using the spread operator.
Image description

# 2.0 Object

2.1 Copy an object:
Image description

2.2 Merging object:
The spread operator allows you to merge two or more objects. If there are conflicting properties, the properties of the object that appears later will overwrite the previous ones.
Image description

# 3.0 Function

3.1 Using Spread in Function Calls :
You can use the spread operator to pass an array as individual arguments to a function.
Image description

Rest Operator:

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.

Default behavior:
Image description
All value support :
Image description
Specific value work using array index :
Image description
Since the rest parameter generates an array, the map will work :
Image description
Combining Arguments Dynamically :
Image description

When to Use the Rest and Spread Operator

Use the rest operator when handling an unknown number of function arguments or collecting remaining elements in array/object destructuring. The spread operator is ideal for expanding arrays/objects into individual elements or passing array items as function arguments.

Table

Image description

Conclusion: Rest vs Spread Operator

The rest operator gathers multiple elements into an array or object, ideal for handling variable arguments in functions or array/object destructuring. The spread operator expands elements from arrays, objects, or strings, simplifying tasks like copying, concatenation, or passing array elements as separate arguments in function calls.

Top comments (0)