Spread Operator — ES6 features-Part-1

Bhagirthi Jhamb
4 min readApr 21, 2020
Spread Operator Syntax

In JavaScript ES6 has brought with it some really interesting features that has added expressive power to the language. Even though these tools allow us to perform some common operations, they are worth understanding because they do their job in a more concise and elegant way. One such new feature is the Spread Operator.

Spread Operator

The spread operator is used to split an array into a list of comma-separated values which can be used in various places such as function arguments or array matching. It allows any iterable value to spread individually inside a receiver. Iterables are anything that can be looped over such as strings, arrays, and sets. Objects are not iterable in JavaScript but spread operator can still be used on objects

Lets see how spread operator works on string. example —

const str = "Hello World !";
console.log(...str); // H e l l o W o r l d !

another example

const str = 'Sunshine';
const arr = [ ...str ];
console.log(arr); // [ "S", "u", "n", "s", "h", "i", "n", "e" ]

Here, the thing that we are expanding is the string str. The three dots act upon the string in the variable str and spread each individual character inside the receiver.

One more example

const words = ['How', 'are', 'you'];
console.log(words);
console.log(...words); // How are you

Here we have an array of strings called words. First, we just print words. The output is ['How', 'are', 'you']. It is same as the words variable itself. Now, we print ...words. We get How are you. Notice that this is not an array anymore. Instead, it is a string. console.log(...words) behaved as this line: console.log('How', 'are', 'you').

The logic is same — Each individual member of the array was plucked from its location and kept inside the receiver. The receiver, in this case, is a function. So the individual items become function arguments.

example

const arrayOne = [1, 2, 3, 4];
const arrayOneCopy = arrayOne;

arrayOne.push("five");

console.log(arrayOne); // [1, 2, 3, 4, "five"]
console.log(arrayOneCopy); // [1, 2, 3, 4, "five"]

Here, changing the original array also changes the copy! This is because unlike primitive values, when we store arrays (as well as regular objects and functions) in variables, the variable still refers to the original object in memory.

A simple solution to this is to spread the array out, creating a new set of individual values, and then to wrap those values in square brackets (collecting them into a new array):

const arrayTwo = [1, 2, 3, 4];
const newArray = [...arrayTwo];

arrayTwo.push("five");

console.log(arrayTwo); // [1, 2, 3, 4, "five"]
console.log(newArray); // [1, 2, 3, 4]

The spread operator allows us to pass an array of arguments into a function as if we were doing it manually one-by-one. This is great because it saves time, plus it doesn’t need to be rewritten every time the array changes.

function multiplyThreeNumbers(a, b, c) {                         
return a * b * c; } let arr = [1, 2, 3]; console.log(multiplyThreeNumbers(...arr)); // 6

Spread Operator on Arrays

The core piece to know is the ... syntax. This is the spread operator, and it essentially takes either an array or an object and expands it into its set of items. This lets you do fancy things, so for example if you have the code:

const array = [1, 2]; 
const array2 = [...array, 3, 4];
console.log(array2); // [1, 2, 3, 4]

The spread operator lets you essentially drop an array in and get its values.

Math.min takes n number of numeric parameters and returns the smallest number in the group.

console.log(Math.min(5, 6, 8, 9, 11, 999));  // 5

Imagine that we don’t know beforehand how many numbers we are going to test. In the above example, there are six. We may have a hundred next time. If we hardcode the numbers like above, we lose the flexibility of checking maximum of more numbers at runtime.

Since we know from above that we can unpack an iterable inside an appropriate receiver, we may be able to solve the problem like this —

const minNum = (numbers) => {
return Math.min(...numbers);
}
console.log(minNum([5, 6, 8, 9, 11, 999])); // 5
console.log(minNum([25, 61, 8, 9, 11, 999])); // 8

The same logic applies here as in the previous examples. Every individual number is plucked from the numbers array and kept inside the receiver. The receiver, in this case, is Math.min() method/function.

Spread Operator on Objects

Next, for objects that spread syntax lets you do the equivalent of Object.assign, copying the values of an object into a new one. Looking at a simple code example:

const obj1 = {a: 6, b: 7}; const obj2 = {c: 8, ...obj1};  // {a: 6, b: 7, c: 8}

A practical example would be if you are creating a shopping cart and you want to add the object data fetched from an API to your cart array as cart item. You would like to add another property with a key of count and with a value of 1. The value for this property can be updated with some logic in the code.

const obj = { id: 1, title: 'item1', price: 22 };
const newObj = { ...obj, count: 1 }
console.log(newObj); //{ id: 1, title: "item1", price: 22, count: 1 }

Advantages

The Spread operator helps us to create a new copy of an array/object that has an updated array/object. We do not modify the original array/object, meaning other parts of our code can call and use the original and new array/object.

The Spread Operator has more than one function. In a sense, it is overloaded. It can also be used as rest operator in conjugation with destructuring. In the Part-2 and Part-3 of this article, we will discuss Rest Parameter and Destructuring.

--

--

Bhagirthi Jhamb

Front-end Web Developer, Bootcamp grad, learning Full-stack Web Development