Uncategorized

JavaScript – Spread Operator (…)

What is the JavaScript spread operator? How do you use it? Why would you use something that looks so ridiculous? This post will hopefully answer these questions.

The spread operator, in simple terms, is a way to “spread” the contents of an array or object. I know, that doesn’t make sense by itself, so let’s get into it.

Let’s take a simple example, starting with two simple arrays:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

Now let’s say you wanted to combine them into one single, larger array?
You could do something like this, though it’s a bit tedious:

let arr3 = [arr1[0], arr1[1], arr1[2], arr2[0], arr2[1], arr2[2]];
console.log(arr3); // [1, 2, 3, 4, 5, 6]

..or, in case you have some large arrays you’re trying to combine and brute forcing it is not an option (most likely the case) you could write a function which does the “spreading” for you:

let combineArrays = (arr1, arr2) => {
let arr3 = [];
arr1.forEach(item => {
arr3.push(item);
});

arr2.forEach(item => {
arr3.push(item);
});

return arr3;
};

console.log(combineArrays(arr1, arr2)); // [1, 2, 3, 4, 5, 6]

As you can see, we’re simply combining two arrays into one larger array containing all of the contents of the two smaller arrays. Simple, but tedious.
Thankfully some brand new JavaScript makes this a whole ‘lot easier…with the spread operator!

Let’s see how we can accomplish the above example with one line of code:

let arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4, 5, 6]

As we can see from the above code, the spread operator takes care of the heavy lifting for us.

You can also do a similar type of thing with objects:

let obj1 = {
a: 'alpha',
b: 'bravo'
};

let obj2 = {
c: 'charlie',
d: 'delta'
};

let obj3 = {
...obj1,
...obj2
};

console.log(obj3); // Contains all the items from obj1 and obj2

Why would you ever use this? Well, whenever you need to combine arrays or objects together quickly.

The spread operator is also useful for updating specific items in an array. For example, we have an array of four objects, and we need to replace the third object in the array with a different object:

let objectArray = [
{ a: 'alpha', b: 'bravo' },
{ c: 'charlie', d: 'delta' },
{ e: 'echo', f: 'foxtrot' },
{ g: 'golf', h: 'hotel' }
];

// replace item 3 (at index 2) with a new object:

objectArray = [
...objectArray.slice(0, 2),
{ n: 'new', o: 'object' },
...objectArray.slice(3)
];

console.log(objectArray); // We replaced "echo" and "foxtrot" with "new" and "object"

Notice we are using the “slice” method of the array object to accomplish this. Slice simply returns a section of an existing array defined by the integer(s) passed into it. Tutorial of the slice method coming soon..

Now let’s take this one step further. Let’s say you have an app which must maintain state. This state is all contained in an array of objects, and you must continue updating this array to reflect this changing state.
So we will create a function which accepts an array of objects (the app’s current state), a new object (the app’s new state), and an index (where the state was changed):

let objectArray = [
{ a: 'alpha', b: 'bravo' },
{ c: 'charlie', d: 'delta' },
{ e: 'echo', f: 'foxtrot' },
{ g: 'golf', h: 'hotel' },
{ i: 'india', j: 'juliet' },
{ k: 'kilo', l: 'lima' },
{ m: 'mike', n: 'november' }
];

let updateState = (arr, newObject, i) => {
arr = [
...arr.slice(0, i),
newObject,
...arr.slice(i + 1)
];

return arr;
};

let newState = updateState(objectArray, { u: 'updated', s: 'state' }, 2);
console.log(newState); // replaces "echo" and "foxtrot" with "updated" and "state"

I hope this helps, and at least makes some sense. You can see a pen of it here.

Please, as always, also educate me on better ways to code in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *