Javascript Spread and Rest Operators

Article Cover

Through the bootcamp where I am a student, I learned about the REST and SPREAD operators, both features of ES6.

However, a publication appeared on my linkedin timeline where the author spoke a little about REST, and when viewing the comments I realized that several developers did not seem to know this wonderful thing yet, and so I decided to write this article to help even more developers. .

SPREAD

Basically the spread operator ... serves to copy data from an array or object and to pass an entire array as a parameter to a function, but when the function does not expect an array but rather separate arguments.

OMG sounds great doesn't it? But how to use it?

const dataUser = ['Michelle', 1964, '1.80m', 'Chicago'];

const newUser = [...dataUser, 'married', 'mom'];

console.log(dataUser); // (4) ['Michelle', 1964, '1.80m', 'Chicago']
console.log(newUser); // (6) ['Michelle', 1964, '1.80m', 'Chicago', 'married', 'mom']

Starting from the above code, we can see that we have the dataUser variable which is an array with the data of a user.

Suppose we want to create a new array newUser that has the same data as dataUser, plus additional data, so we use the spread […nameArray, additionaldata].

So, running a console.log on our 2 arrays, we see that dataUser has 4 positions and newUser has 6, as it has everything from dataUser plus marital status and city as additional data.

We can also just copy the data from the array or object we want and put it in a new variable, nothing stops us:

const dataUser = {
  name: 'Ilda',
  age: 23,
  office: 'developer',
}

const newuser = { ...dataUser }

console.log(dataUser) // {name: 'Ilda', age: 23, office: 'developer'}
console.log(newUser) // {name: 'Ilda', age: 23, office: 'developer'}

With this, the dataUser and newUser objects will have the same contents.

Another way to use the spread is in functions, especially those that require a considerable amount of parameters. Using the example below, our sum() function expects three parameters, where it will return the sum of the 3.

If we didn't have the spread, we would have the two options below to send parameters to our function, option 2 being the 'worst' way, let's say.

const date = [2, 8, 6]

function sum(x, y, z) {
  return x + y + z
}

sum(1, 2, 3) // Option 1
sum(data[0], data[1], data[2]) // Option 2

With the spread we would only need:

const date = [2, 8, 6]

function sum(x, y, z) {
  return x + y + z
}

console.log(sum(...data)) // 16

What the spread does in the above example is “break the array” where each position becomes an argument variable.

We can also combine (one or more) arrays or (one or more) objects:

const firstName = ['Ilda']
const surname = ['Neta']
const fullName = [...firstName, ...surname]

console.log(fullName) // (2) ['Ilda', 'Neta'];

console.log(...fullName) // Ilda Neta

Note that in the example above, I also used the spread in console.log, so it already shows my fullName array 'spread out'.

Rest

rest is used when we want to retrieve the rest of the contents of objects and vectors, allowing us to transform an indeterminate number of parameters into a new array.

Following the spread line, the rest has the same declarative form for use, …arrayname or …objectname, however the rest is always used at the end and the way of naming the variables is also different, because the rest uses the destructuring model.

Let's go to the examples:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8]
const [one, two, three, four, ...restNumbers] = numbers

console.log(one) // 1
console.log(four) // 4
console.log(restNumbers) // (4) [5, 6, 7, 8]

As above, the numbers array has numbers, but if we want to use some numbers in separate variables, just create a new array passing the name that these variables will have and the rest of the data that we don't want in separate variables, we can transform it them into another array.

In this case, the restNumbers is an array derived from numbers that has the rest of the numbers that we didn't separate.

const person = ['Michelle', 1964, '1.80m', 'Chicago', 'MIT']

const [name, yearBirthday, height, ...personData] = person

console.log(name) // Michelle
console.log(height) // 1.80m
console.log(personData) // (2) ['Chicago', 'MIT']

The names that we will give to our variables must follow the order of the position of the items in the array, in this case, name is equivalent to position[0] of person, as well as yearBirthday is equivalent to position[1] and so on.

rest also works with objects, but it is a different destructuring process and I think it deserves an article of its own.

I hope you were able to understand the value of these operators in our daily lives, as they are a hand in the wheel.

And if you use React for example, the spread is very valuable to set values in states, since React starts from the principle of immutability.

A hug and I'm waiting for you in the next article! 👋🏻