Understanding the Spread Operator in JavaScript

Understanding the Spread Operator in JavaScript

What is the spread operator? In JavaScript, spread syntax refers to the use of an ellipsis of three dots ( … ) to expand an iterable object into the list of arguments. The spread operator was added to JavaScript in ES6 (ES2015), just like the rest parameters, which have the same syntax: three magic dots

The first time I looked at this I was really confused about what it was supposed to mean, or even do, but harnessing the power of the spread operator in JavaScript has definitely payed off.

In my latest entry to Hands-on Vue for Beginners series, I used a spread operator in the tutorial and promised I would make a post explaining what it is, and how it works, for anyone that is not yet familiar with it.

Disclaimer. The spread operator is an ES6 feature, and thus is not supported in every browser (IE strikes again). However you can rest assured that it will work on all major and modern browsers. Browser Compatibility

Diving in

MDN explains it like this:

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. And I don’t know about you, but for me when I was trying to learn all this it was super daunting and confusing. So let’s break it down to digestible pieces.

Imagine you have a function, where you want to add three values:

function add(a, b ,c) {
  return a + b + c;

Now imagine, you have an array of values:

const values = [1, 2, 3];

Now, if we ask ourselves, how would we go about putting those values into the function add them. A practical approach would be to maybe do something like this:

const sum = add(values[0], values[1], values[3]);

I mean, it sort-of works. Right? But take it up a nudge, what happens when you have a function that will accept a dynamic number of arguments? Or even simpler yet, what if we have a scenario where this function wants 20 values and I give you an array with 20 numbers.

This is when things start to get really ridiculous, are you going to access all the values directly via index? (There’s ways to do this with array functions like reduce, I know, but bare with me for the sake of example.)

Consider the following example:

function sum(a,b,c,d,e,f,g,h,i,j,k,omgwhy) {
 return a+b+c+d+e+f+g+h+i+j+k+omgwhy;

const values = [1,2,3,4,5,6,7,8,9,11,12];

Here’s where the spread operator shines! Imagine that this values array is a box, it contains all these numbers in it in a VERY neat and orderly fashion, each one has an index - and that contains it perfectly.

When we access an array’s index value like this values[1] we are very neatly taking out that single value, which is what we did on the first example. But to continue with the metaphor, what if we wanted to take out ALL the values in the exact order in which they are in the box?

Maybe it could be cool to be able to do something like this values[0-11], but instead we type it like this ...values.

Now in this case in particular with the function, you would say:

const result = sum(...values);

Tada! Now, watch carefully because when take the values out of the array they’re not just getting thrown around into the wind, they’re all going into their respective parameters in the function. a will get 1b will get 2 and so on.


Alright, so spreading arrays into functions is nice. But i’ve honestly not used it a lot. However merging two arrays together or two objects becomes a breeze!

Let’s cook up an example:

const favoriteGames = ['Zelda', 'Metroid'];
const favoriteBands = ['Queen', 'RHCP'];

const lifeFavorites = [...favoriteGames, ...favoriteBands];

So first we’re just defining a couple of arrays for examples, favoriteGames and favoriteBands. But let’s take a look closely at the third line.

const lifeFavorites = we’re going to store the result of the merge here, nothing too fancy and we’re setting it to be equal to a NEW array.

Notice = [somestuffshere];

This is super important to understand, when you spread an array or an object those spread values needs to be used somehow, you need to clean up after yourself. So in this case we’re saying:

Ok, JS, grab the contents of these two array boxes, dump all the crap they have in them into this new box and call it lifeFavorites. Thankfully the actual crap-dumping is done in a very orderly fashion and order of the values will be respected.

So the result will actually be:

['Zelda', 'Metroid', 'Queen', 'RHCP']

Making copies

Another great way to use the spread operator is to make a copy of an array or an object. In JavaScript when you assign an object or array to a variable you’re actually storing something called the “pointer”, which sort of works like the address of where that object is being stored.

So if you do:

const obj = {name: 'Marina'};
const anotherObj = obj;

The big problem here will be that both obj and anotherObj are actually pointing to the same object. So if you change one or the other, they will both change because the pesky pointer is addressed to the same object.

In frameworks like Vue this becomes a real problem and a real pain to debug, because in some cases like when making copies of props you never want to modify the original object. In React this is also used when changing the state, you’re not supposed to directly modify the value.

So how do we make a copy with the spread operator?

const baseObject = {name: 'Marina'};
const myCopy = {...baseObject};

const baseArray = [1, 2, 3];
const arrayCopy = [...baseArray];

That’s it! Once again, we’re pouring out our boxes into another box that contains it, and that will ensure that the resulting object/array are actually a copy of the original - and you can safely modify them without fear of messing with the first.

javascript web-development programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

What Garbage Collection in JavaScript Is and How It Works

JavaScript values are allocated when things are created (objects, Strings, etc.) and freed automatically when they are no longer used. This process is called Garbage collection.

What Javascript Spread Operator is, How It Works and How to Use It

JavaScript spread operator is one of the more popular features that were introduced in ES6. This tutorial will help you understand it. You will learn what spread operator is and how it works. You will also learn how to use it to copy and merge arrays and object literals, insert data and more.

Top 10 Web Development Trends in 2020 | Web Development Skills

Top 10 Web Development Trends in 2020 will provide you with a detailed list of the trends which are currently being noticed. Upskilling to these trends will help you in landing onto better jobs in 2020-2021.