Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Spread Operator?
3.
Spread Operator Use Cases
3.1.
1. Combining Arrays
3.2.
2. Passing Arguments to Functions
3.3.
3. Merging Objects
4.
What is a Rest Operator?
5.
Rest Operator Use Cases
5.1.
1. Handling Multiple Function Arguments
5.2.
2. Array Destructuring
6.
Difference between Spread and Rest Operator in JavaScript
7.
Frequently Asked Questions
7.1.
What is rest in JavaScript?
7.2.
What is the full form of REST?
7.3.
Can I use Spread and Rest Operators in any JavaScript version?
7.4.
Can the Spread Operator be used with any data type?
8.
Conclusion
Last Updated: May 15, 2024
Easy

JavaScript Spread and Rest Operators

Author Ravi Khorwal
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In modern JavaScript, two handy operators play a crucial role in handling arrays and objects more effectively: the Spread Operator and the Rest Operator. Despite sharing the same syntax (three dots ...), their purposes and usage are different. 

Difference between Spread and Rest Operator in JavaScript

This article elucidates the differences between the Spread and Rest Operator with examples.

What is a Spread Operator?

The Spread Operator, denoted by three consecutive dots (...), is a feature introduced in JavaScript (ES6) used for expanding elements of an iterable (like an array or string) into individual elements. It allows for concise syntax when working with arrays, enabling operations like concatenation, copying, and passing array elements as function arguments with ease. Additionally, it can be used in object literals for shallow copying and merging objects.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Spread Operator Use Cases

The Spread Operator (...) in JavaScript offers versatile functionality, enhancing code readability and conciseness in various scenarios.

1. Combining Arrays

The Spread Operator simplifies the process of combining arrays by expanding the elements of one or more arrays into a new array.

Example:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]

2. Passing Arguments to Functions

Passing array elements as individual arguments to functions becomes effortless with the Spread Operator, enabling cleaner and more flexible function calls.

Example:

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // Output: 6

3. Merging Objects

The Spread Operator facilitates the merging of objects by shallow copying their properties into a new object.

Example:

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // Output: { a: 1, b: 2, c: 3, d: 4 }

These use cases demonstrate the versatility and utility of the Spread Operator in JavaScript programming, offering elegant solutions to common tasks.

What is a Rest Operator?

The Rest Operator, denoted by three consecutive dots (...), is a feature introduced in JavaScript (ES6) used for gathering the remaining elements of an iterable (like an array) into a single array variable. It allows functions to accept an indefinite number of arguments, simplifying function definitions and enabling more flexible parameter handling. Additionally, it can be used to capture remaining object properties not explicitly assigned to other variables during object destructuring.

Rest Operator Use Cases

The Rest Operator (...) in JavaScript provides flexibility and simplicity in handling variable numbers of elements or properties.

1. Handling Multiple Function Arguments

Here's how you can use the Rest Operator to handle multiple arguments in a function:

function sum(...numbers) {
  return numbers.reduce((acc, number) => acc + number, 0);

console.log(sum(1, 2, 3, 4, 5)); // 15

This way, you can pass any number of arguments, and they'll be gathered into an array.

2. Array Destructuring

In array destructuring, the Rest Operator allows for capturing remaining elements of an array into a single variable, making it easier to work with arrays of varying lengths.

Example:

javascript

Copy code

const [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first);  // Output: 1 console.log(second); // Output: 2 console.log(rest);   // Output: [3, 4, 5]

In this example, the Rest Operator (...rest) gathers the remaining elements of the array [1, 2, 3, 4, 5] after the first two elements are assigned to first and second variables, respectively. The gathered elements are then stored in the rest array variable.

Difference between Spread and Rest Operator in JavaScript

FeatureSpread OperatorRest Operator
SyntaxUses three dots (...) before an iterable objectUses three dots (...) before a variable name
Use CaseUsed to expand elements of an iterableUsed to gather remaining elements into an array
ContextTypically used in function calls or array literalsTypically used in function parameters or array destructuring
Exampleconst arr = [...array1, ...array2];const [first, second, ...rest] = [1, 2, 3, 4, 5];
Use in Function CallsmyFunction(...args);function myFunction(first, second, ...rest) {...}
Use in Array Literals[...array1, ...array2];[first, second, ...rest] = [1, 2, 3, 4, 5];

Frequently Asked Questions

What is rest in JavaScript?

In JavaScript, the Rest Operator (...) is used to gather the remaining elements of an iterable (like an array) into a single variable, simplifying function parameter handling and array destructuring.

What is the full form of REST?

The full form of REST is Representational State Transfer. It is an architectural style for designing networked applications, commonly used in web services and APIs to facilitate communication between client and server.

Can I use Spread and Rest Operators in any JavaScript version?

Spread and Rest Operators are supported in ECMAScript 6 (ES6) and later versions of JavaScript. However, support for these operators may vary in older browsers or environments that do not fully implement ES6 features.

Can the Spread Operator be used with any data type?

The Spread Operator (...) can be used with any iterable data type in JavaScript, such as arrays, strings, and other iterable objects. It allows for expanding the elements of the iterable into individual elements or properties.

Conclusion

The Spread and Rest Operators are powerful additions to modern JavaScript, providing concise ways to handle arrays and objects. While they share the same syntax, their context and functionality are distinct. The Spread Operator is used to 'spread' an iterable into its elements, while the Rest Operator 'collects' multiple elements into an array. Understanding these operators can greatly enhance code readability and efficiency, making them essential tools for contemporary JavaScript development.

Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Previous article
JavaScript Array forEach() Method
Next article
Line Break in JavaScript
Live masterclass