Destructuring vs. Rest

Destructuring vs. Rest

Photo by The Creative Exchange on Unsplash

How are Destructuring and Rest similar like the Bryan Cranston twins you ask?

bryan-cranston-the-shining.png

Well, destructuring and rest both unpack values from arrays, or properties from objects, and set them to local variables.

unpack.png

How are they different?

Destructuring takes out the values and sets the new variables to those values. It does not put those values in new arrays or objects.

Rest will take out the values but will always put them in a new array or object, depending on whether you are working with an array or object.

Let's say we used rest on the object below. Will changing a property on the rest's object mutate the original object? In other words, is the original object and rest's object referring to or pointing to the same object in memory?

point.png

Let's try this example and see!:

Here is an object named "person" of one of my favorite sleuths:

crumb-object.png

crumb.jpg

We will destructure it and use rest:

Screen Shot 2021-05-06 at 11.32.43 AM.png

A new variable "rest" is created:

crumb-rest.png

Let's change his age to 43:

Screen Shot 2021-05-06 at 11.33.06 AM.png

Will it change the original object's age? Let's console.log and find out.

The value of rest's age changes to 43: age.png

The original array, person, stays the same!: original-same.png

As you can see from the example above the new rest variable is a brand new object with a new reference "arrow" pointing to a completely new and different object than the original person object.

Thank you for reading! Dev Duffy out!

#javascript
 
Share this