Understanding Rest and Spread Operator | ES6 Guide

Deepak Kumar
Sep 19 · 2 min read
Rest and Spread Operator | ES6 Guide by Deepak Kumar

Spread and Rest Operators are denoted by ... three dots. These three dots can be used in 2 ways, one as Spread Operator and others as Rest Parameter

So, Let's understand what exactly these Spread and Rest operators do?

Rest Operator

  • It collects all the remaining elements into an array.
  • Rest Parameter can collect any number of arguments into an array.
  • Rest Parameter has to be the last arguments.

Here is an example of Rest an operator.

Without Using Rest Parameter : ES5 Implementation

// Write a Function to print sum of arguments.

function add() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum = sum + arguments[i];
return sum;

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

console.log(add(1, 3, 4)); // 8

Example Using Rest Operator: ES6 Implementation

// Write a Function to print sum of arguments.

function add(...args) {
let sum = 0;
for (let i of args) {
sum += i;
return sum;

console.log(add(3, 4, 5, 10, 20)); // 42

console.log(add(1, 3, 4)); // 8

Spread Operator

  • It allows iterables like arrays / objects /strings to be expanded into single arguments/elements.
  • Spread operator is opposite of Rest Parameter. In Rest Parameter We were collecting the list of arguments into an array, while with spread operator we can unpack the array elements.

Let’s see an example to understand spread operator.

    ## EXAMPLE - 1

const cars = ['BMW', 'Audi'];
const moreCars = ['Maruti', 'Swift', ...cars];

console.log(moreCars); // ['Maruti', 'Swift' 'BMW', 'Audi'];

## EXAMPLE - 2 //Copying one array to other

const array1 = [1, 2, 3];
const copiedArray = ...array1;

console.log(copiedArray); // [1, 2, 3]

ES6 has a lot of new features like Template literals, Default Arguments, Arrow Functions, Array and Object Destructuring, Map, Reduce and Filter, Rest and Spread Operator, Object Literals, Classes and a lot more.

If you write code in a javascript and still not familiar with ES6 concepts. You should consider googling these topics.

Here I have written a comprehensive guide to learn ES6, please consider checking out.


Give some clap if you liked the article !!

For more content like this follow me on -> Twitter | Instagram | LinkedIn

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade