A Beginners Guide to using the Spread Operator in JavaScript

Kaiz Hudda
Vue.js Developers
Published in
2 min readAug 3, 2019
How to use the spread operator in JavaScript

Thanks to the introduction of ES6, writing JavaScript code has never been so dynamic. It is definitely a breath of fresh air. One standout feature that I use regularly is the spread operator. I personally believe, every JavaScript developer whether their using React.js, Vue.js, or using ES6 in general should have this skill in their toolkit. Lets take a closer look at the spread operator.

What is Spread?

The spread operator is the shortest and most simplest method to copy enumerable properties from a provided object to another newly created object.

Note: The spread operator is denoted by three dots ( ... ).

Using Spread with JavaScript Objects

Combining Objects

Spread operators with objects are usually used to make a copy of an existing object or to make a new object but expand it with more properties.

The below example adds the key, values from the num1 object to num2.

const num1 = { a: '1', b: '2', c: '3'};const num2 = { ...num1, d: '4', e: '5'};// num2 = { a: '1', b: '2', c: '3', d: '4', e: '5' }

How about a more exciting example?

We have all used Math.max at some point when learning how to use JavaScript. Basically, Math.max takes n number of parameters and returns the largest number from it.

An example:

Math.max(5, 10, 30, 1, 3); 
// 30

The problem with this technique is that, it is hard coded in. What if we want to dynamically pass in more or less numbers at runtime. We can solve this by using the spread operator.

const num = [5, 10, 30, 1, 3];Math.max(...num);
// 30

By spreading the num array in this way, the Math.max will automatically retrieve each individual element in the num array as an argument to the function. In this way we can also reduce or expand the array at runtime.

Much more flexible isn’t it? 💪💪💪

Using Spread with Arrays

Similarly to objects we can use the spread operator with arrays too. Lets have a look at how we can achieve this.

Combining Arrays

The below example, adds arr items to the start of arr2.

const arr = [1, 2, 3, 4];const arr2 = [...arr, 5, 6];
// arr2 = [1, 2, 3, 4, 5, 6]

You can even place elements at any point within the array.

const arr = [1, 2, 3, 4];const arr2 = [5, ...arr, 6];
// arr2 = [5, 1, 2, 3, 4, 6]

Its just that simple! ✔✔✔

Have you used the spread operator yet?

If you found this guide useful, please don’t forget to hit that 👏 button, and by sharing it with your friends on social media.

If you want to learn more or would like to follow my journey, follow me on Twitter, @KaizHudda.

--

--

Kaiz Hudda
Vue.js Developers

Just a Frontend Developer documenting his journey.