DEV Community

KelahKelah
KelahKelah

Posted on • Updated on

Es6 Spread and rest operator in javascript

Have you ever come across three dots such as …myVariable in a legacy code and wondered what in the world that is? Well you’re not alone bro. I’ve been there too. But don’t worry, what you saw was just another ES6 spread and rest operator that allows you copy or condense one or more iterables respectively into one variable.

In this article i would talk about ES6 spread and rest operator and how to use it to write a more readable code.

Spread operator

Before the Es6 spread operator, if we wanted to spread an array so as to combine them with another one, we would us the concat() array method to spread two arrays like so

const arr1 = [‘true’ , ‘false’];
const arr2 = [‘yes’ , ‘no’];
const addArr = arr1.concat(arr2)
console.log(addArr)
//Prints
[‘true’, ‘no’, ‘yes’, ‘no’]
Enter fullscreen mode Exit fullscreen mode

But with the ES6 Spread operator all you need to do is

const arr1 = [‘true’ , ‘false’];
const arr2 = [‘yes’ , ‘no’];
const addArr = […arr1, …arr2]
console.log(addArr)
//Prints
[‘true’, ‘false’, ‘yes’, ‘no’]
Enter fullscreen mode Exit fullscreen mode

You can also do the same with objects.
Lets say you have

const userData = {name: ‘kelechi’, age: 25, gender: ‘female’};
const userRole = {isAdmin: true, isLoggedIn : false};
const mySpread = {…userData, …userRole}
console.log(mySpread)
//Prints
{name: ‘kelechi’, age: 25, gender: ‘female’, isAdmin: true, isLoggedIn : false}
Enter fullscreen mode Exit fullscreen mode

Rest operator

Even though rest operator has the same syntax as spread, they do the exact opposite thing. Strange right? Exactly. So say you want to bundle up different arrays as one variable, you should use the rest operator. While this explanation may seam daunting at first, i will use the ES6 destructuring assignment to show you how to understand it better.
in a nutshell, destructuring assignment is used to unpack the elements in an object to make it easier to access. You can read up more on java script destructing here.

const myData = [‘miss’, ‘kelechi’, 25, ‘female’, true];
const destructured = [title, firstName, …restData]
console.log(title) // miss;
console.log(firstName) //kelechi;
console.log(resData) //[25, female, true]
Enter fullscreen mode Exit fullscreen mode

You see that we used the rest operator to access the rest of the data, ‘rest’ as the name implies.

In conclusion, spread operators are used to copy arrays in arrays or even objects into objects while rest operators allows you to bundle the rest of the elements in an array or objects in an element as one variable.

Discussion (0)