Understanding the Spread Operator in JavaScript

Understanding the Spread Operator in JavaScript

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.

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.


Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Svelte.js - The Complete Guide

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Advanced CSS and Sass: Flexbox, Grid, Animations and More!

☞ CSS - The Complete Guide (incl. Flexbox, Grid & Sass)

☞ CSS Bootcamp - Master CSS (Including CSS Grid / Flexbox)

☞ Build Responsive Real World Websites with HTML5 and CSS3

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)

☞ JavaScript - Step By Step Guide For Beginners


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

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.