Skip to content

Tricks with Spread Operator in JavaScript

Last updated on February 28, 2020

In this post, I am going to share about the usage of Spread operator in JavaScript along with the use cases.

Introduction

First of all, what does it mean by spread operator is that spreading the elements and it’s widely used for working with array and objects.

Spread operator can be identified with the notation of ... . But the same notation is shared by another operator called as rest which I will share that in next post.

Let’s say we have userName array variable.

const userNames = ['Srinivasan', 'John', 'Rajan'];

// To copy this array variable into other array, then
const names = [ ...userNames ];

Note

The important thing to keep in mind here is that, ... operator can not be used as a standalone.

const User = {
  firstName: 'Srinivasan', 
    lastName: 'KK',
};

const newUser = {
   ...User
};

The above newUser object will have all the properties of User object, but if you do like this const newUser = …User; you will get an error. Always ... operator needs some surrounding block to work.

Use cases

  • To create a copy of an object
  • To create a copy of an array

Both use cases will be using Object and Array literal way of doing and will create a shallow copy so references will not get affected.

References

Published inJavaScriptReact