Destructuring in Vanilla JS for Beginners
Tags: javascript, arrays, objects, beginners
Published: 2021-07-20 17:22:52

Destructuring is a very useful way for accessing multiple properties within an array or an object in Javascript.  Learning this technique is going to be essential if you are planning to learn React in the future.  Even if you do not plan to learn React, this technique is also a great way to make your code cleaner and easier to work with.  

## What is Desctructuring?

When you destructure an array or object you are converting it to a smaller array, object, or variable.

## Array Destructuring 

Below we have two arrays to work with:
```javascript
const jedi = ['Yoda', 'Qui Gon Jinn', 'Obi Wan Kenobi', 'Luke SkyWalker']
const sith = ['Emperor Palpatine', 'Darth Vader', 'Darth Maul', 'Kylo Ren']
```
If we wanted to access each jedi we would have to do something like this:
```javascript
console.log(jedi[0])
console.log(jedi[1])
console.log(jedi[2])
console.log(jedi[3])
```
In our console we would get:
```javascript
Yoda
Qui Gon Jinn
Obi Wan Kenobi
Luke SkyWalker
```
This is a tedious way of accessing each jedi in our jedi array.
Instead, let's destructure our jedi array:
```javascript
const [firstJedi, secondJedi] = jedi
console.log(firstJedi)
```
In our console this would print:
```javascript
Yoda
```
We took the array we wanted to destructure and put it on the right side and assigned it to some variable names. Each variable's position will correspond with each element in the array we are destructuring.  For example:
```javascript
const [firstJedi, secondJedi] = jedi
console.log(secondJedi)
```
Will print:
```javascript
Qui Gon Jinn
```
What if we wanted to combine both the jedi and the sith arrays?  To do this we can use the __spread operator__ (...):
```javascript
const jedi = ['Yoda', 'Qui Gon Jinn', 'Obi Wan Kenobi', 'Luke SkyWalker']
const sith = ['Emperor Palpatine', 'Darth Vader', 'Darth Maul', 'Kylo Ren']


const jediVsSith = [...jedi, ...sith]

console.log(jediVsSith)
```
Our console will print:
```javascript
Yoda
Qui Gon Jinn
Obi Wan Kenobi
Luke SkyWalker
Emperor Palpatine
Darth Vader
Darth Maul
Kylo Ren
```
![Darth Maul fighting Obi Wan & Qui Gon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tr2fqppkotpylj2qmdye.gif)
Destructuring allows us to access elements within our arrays in a way that is easier to read by assigning each element to a variable name of our choosing without having to use bracket notation.
## Object Destructuring
Destructuring an object is going to be very similar to an array only we will be using curly braces __{}__.  Below we have two objects:
```javascript
const darthVader = {
  age: 45,
  lightSaber: 'red',
  famouseLine: 'I am your FATHER!!'
}

const yoda = {
  age: 900,
  lightSaber: 'green',
  famouseLine: 'Fear is the path to the darkside.'
}
```
If we want to access yoda's age and lightsaber:
```javascript

const { age, lightSaber } = yoda

console.log(age)
console.log(lightSaber)
```
Our console:
```javascript
900
green
```
Instead of our variables being based on position like it was with arrays, they will be based on the name of the key instead.  The names of the variables must match the names of the keys. 
### What if we want to use a different variable name?
```javascript
const { age: yodaAge, lightSaber: yodaLightSaber } = yoda

console.log(yodaAge)
console.log(yodaLightSaber)
```
Our console will give the same results:
```javascript
900
green
```
### What if we want to add a default value to a key that yoda does not already have?
```javascript
const { age: yodaAge, lightSaber: yodaLightSaber, anotherYodaQuote = 'The greatest teacher, failure is.' } = yoda

console.log(yodaAge)
console.log(yodaLightSaber)
console.log(anotherYodaQuote)
```
By doing this our console will show our added default value but does not actually add the key/value pair to our yoda object:
```javascript
900
green
The greatest teacher, failure is.

```
### Using the spread operator(...) with object destructuring:
```javascript
const {age, ...rest} = yoda

console.log(rest)
```
Console:
```javascript
lightSaber: 'green'
famouseLine: 'Fear is the path to the darkside.'
```
Using the __spread operator__ we accessed the rest of yoda's properties except for the age property because we already declared it.  The variable __rest__ to the right of the spread operator can be a variable name of your choosing.
### Combining objects using the spread operator(...)
Let's remove some properties to each object and see what happens:
```javascript
const darthVader = {
  
  lightSaber: 'red',
  famouseLine: 'I am your FATHER!!'
}

const yoda = {
  age: 900,
  lightSaber: 'green',

}

const newJedi = {...darthVader, ...yoda}

console.log(newJedi)
```
Console:
```javascript
age: 900
lightSaber: 'green'
famouseLine: 'I am your FATHER!!'
```
Notice how when we combined our objects, properties from the second object (__yoda__) were added to the first object (__darth vader__) if they were not already there and would also override the first object's property if they both had the same property.
## Conclusion
There are many more use cases for destructuring arrays and objects within functions.  If you are a beginner like me, it might take some time to wrap your head around this topic, but that is OKAY!  Check out the links below if you want to dive deeper into this topic. 
![A yoda meme telling you to be patient and learn](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2cosb6tymrz8p663zmy.jpeg)
If you plan to learn React, becoming more comfortable with this technique will make life easier when you start working with __props__ and __components__.  Stay tuned for __Part II__ of this blog topic where we will destructure some props and components within functions in React!
## Resources
[MDN Destructuring Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
[freeCodeCamp Javascript Object Destructuring](https://www.freecodecamp.org/news/javascript-object-destructuring-spread-operator-rest-parameter/)