DEV Community

Cover image for Destructuring in Vanilla JS for Beginners
Josh Blengino
Josh Blengino

Posted on • Updated on

Destructuring in Vanilla JS for Beginners

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:

const jedi = ['Yoda', 'Qui Gon Jinn', 'Obi Wan Kenobi', 'Luke SkyWalker']
const sith = ['Emperor Palpatine', 'Darth Vader', 'Darth Maul', 'Kylo Ren']
Enter fullscreen mode Exit fullscreen mode

If we wanted to access each jedi we would have to do something like this:

console.log(jedi[0])
console.log(jedi[1])
console.log(jedi[2])
console.log(jedi[3])
Enter fullscreen mode Exit fullscreen mode

In our console we would get:

Yoda
Qui Gon Jinn
Obi Wan Kenobi
Luke SkyWalker
Enter fullscreen mode Exit fullscreen mode

This is a tedious way of accessing each jedi in our jedi array.
Instead, let's destructure our jedi array:

const [firstJedi, secondJedi] = jedi
console.log(firstJedi)
Enter fullscreen mode Exit fullscreen mode

In our console this would print:

Yoda
Enter fullscreen mode Exit fullscreen mode

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:

const [firstJedi, secondJedi] = jedi
console.log(secondJedi)
Enter fullscreen mode Exit fullscreen mode

Will print:

Qui Gon Jinn
Enter fullscreen mode Exit fullscreen mode

What if we wanted to combine both the jedi and the sith arrays? To do this we can use the spread operator (...):

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)
Enter fullscreen mode Exit fullscreen mode

Our console will print:

Yoda
Qui Gon Jinn
Obi Wan Kenobi
Luke SkyWalker
Emperor Palpatine
Darth Vader
Darth Maul
Kylo Ren
Enter fullscreen mode Exit fullscreen mode

Darth Maul fighting Obi Wan & Qui Gon
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:

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.'
}
Enter fullscreen mode Exit fullscreen mode

If we want to access yoda's age and lightsaber:


const { age, lightSaber } = yoda

console.log(age)
console.log(lightSaber)
Enter fullscreen mode Exit fullscreen mode

Our console:

900
green
Enter fullscreen mode Exit fullscreen mode

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?

const { age: yodaAge, lightSaber: yodaLightSaber } = yoda

console.log(yodaAge)
console.log(yodaLightSaber)
Enter fullscreen mode Exit fullscreen mode

Our console will give the same results:

900
green
Enter fullscreen mode Exit fullscreen mode

What if we want to add a default value to a key that yoda does not already have?

const { age: yodaAge, lightSaber: yodaLightSaber, anotherYodaQuote = 'The greatest teacher, failure is.' } = yoda

console.log(yodaAge)
console.log(yodaLightSaber)
console.log(anotherYodaQuote)
Enter fullscreen mode Exit fullscreen mode

By doing this our console will show our added default value but does not actually add the key/value pair to our yoda object:

900
green
The greatest teacher, failure is.

Enter fullscreen mode Exit fullscreen mode

Using the spread operator(...) with object destructuring:

const {age, ...rest} = yoda

console.log(rest)
Enter fullscreen mode Exit fullscreen mode

Console:

lightSaber: 'green'
famouseLine: 'Fear is the path to the darkside.'
Enter fullscreen mode Exit fullscreen mode

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:

const darthVader = {

  lightSaber: 'red',
  famouseLine: 'I am your FATHER!!'
}

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

}

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

console.log(newJedi)
Enter fullscreen mode Exit fullscreen mode

Console:

age: 900
lightSaber: 'green'
famouseLine: 'I am your FATHER!!'
Enter fullscreen mode Exit fullscreen mode

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
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
freeCodeCamp Javascript Object Destructuring

Top comments (0)