The Spread Operator in JavaScript is great to have in your toolkit when working with Arrays and Objects. It can take any iterable, and expand it into its constituent parts.

Spread Operator Syntax

The syntax for the Spread Operator is an ellipsis (…) preceding the variable name. Admittedly, this description is a little confusing, so here are some examples:

// When used with array literals
const anArray = [1, 2, 3];
const anotherArray = [...anArray, 4, 5, 6];

// And with object literals
const anObject = { key: "value" };
const clonedObject = { ...anObject };

Not too bad so far, but here’s a note: There is another operator, the Rest operator, with exactly the same syntax. What’s the difference, then? Context. When used on parameters in a function call, this is when it becomes the Rest operator. Since we are focused on the Spread Operator in this article, we won’t talk about Rest here.

Strings

When used on a string or a string literal, you can very easily create a character array:

const myString = "Example";
const charArray = [...myString]; // ["E","x","a","m","p","l","e"]

Note the brackets on line 2 around [...myString] – don’t forget these, or you’ll get a syntax error!

This method can be useful if you wish to modify a particular letter (or letters) in a string. We can already use bracket notation on a string in JavaScript to read a character, but we cannot modify it. The character array allows us to do this.

const myString = "Example";

// Doesn't work:
myString[1] = "X";

// But this does:
const charArray = [...myString];
charArray[1] = X;
const newString = charArray.join(""); // "EXample"

Arrays

The spread operator also gives us a great way to copy arrays as well:

const arrayOne = [1, 2, 3];
const arrayTwo = [...arr];
// arrayOne and arrayTwo are now in two different locations in memory, so:
arrayOne !== arrayTwo; //is true

// we can also modify arrayTwo, and the contents of arrayOne will remain unchanged:
arrayTwo.push(4);
// arrayOne is still: [1, 2, 3]
// arrayTwo is now: [1, 2, 3, 4]

Pretty easy, right? Short, sweet, and to the point.

With arrays, we also get an easy way to concatenate two arrays together:

const arrayOne = [1, 2, 3];
const arrayTwo = [4, 5, 6];

const combined = [...arrayOne, ...arrayTwo];
// combined is now [1, 2, 3, 4, 5, 6];

This can be much easier to read than using Array.prototype.concat() to join two arrays together. And this method does not modify the original arrays as some built-in array methods do, so mutability is not a problem here. No unexpected side-effects!

Objects

Objects work much the same as arrays do, but there are some differences. The first thing to note is that we should not use brackets, as objects are not iterable. Instead, make sure to use curly braces.

That being said, we do gain the ability to copy objects easily, just as we do with arrays:

const person = {
  firstName: "Will",
  lastName: "Parks"
};

const clonedPerson = { ...person };

// as before with arrays, person and clonedPerson are now at two different locations in memory, so:
person !== clonedPerson // is true again

One of my favorite ways to take advantage of this is that we are now able to copy an object, and modify the new object all in one go. For example:

const person = {
  firstName: "Will",
  lastName: "Parks"
};

const clonedPerson = {
  ...person,
  firstName: "William"
};
// So now:
person.firstName === "Will"
clonedPerson.firstName === "William"

// The above assignment of clonedPerson is the equivalent of:
// (This is just for demonstration -- please don't ever do this!!)
const clonedPerson = {
  firstName: person.firstName,
  lastName: person.lastName,
  firstName: "William"
};

In the above example, even though person already has a property called firstName, and we’re copying it (and its value) over to clonedPerson, we are immediately overwriting it with a new value. This is particularly useful if you are, say, updating state in React, and need to update just a few values while keeping the rest intact.

Spread Operator in Function Calls

This may come a bit naturally, after seeing how the spread operator works with arrays, but it’s worth mentioning anyhow.

We can use this operator when calling a function, to assign the elements of an array directly to the function’s arguments:

function someFunction(a, b, c) {
  //does something
}

const data = ["foo", "bar", "baz"];

//The below will call someFunction with
// a === "foo", b === "bar", c === "baz"
someFunction(...data);

// This can also be mixed between an array of data, and some other argument form:
const shorterData = ["foo", "bar"];
someFunction(...shorterData, "baz"); // equivalent to the function call on line 9

To see the official docs for the spread operator, check out the official docs on mozilla.org.

I hope this gave you a good understanding of how the spread operator is used! If you have any more tricks on ways that it can be used, drop a comment below – I’d love to hear about it!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply