DEV Community

Corbin Arnett
Corbin Arnett

Posted on

Destructuring JavaScript Objects

Destructuring is a super useful feature in the latest Javascript update(ES6), but honestly wasn't something that I took full advantage of until recently. Let's dive in.

Destructuring allows us to pull data out of arrays and objects and set them into their own variable. Lets take a look at a basic JS Object:

const album = {
  title: 'A Kind of Blue',
  artist: 'Miles Davis',
  genre: 'Jazz',
  release_year: 1959,
  label: 'Columbia'
};

Traditionally to extract a variable from this object you see something like the following:

const artist = album.artist
const genre = album.genre

As you can see, this can be a very repetitive process which destructuring allows us to improve upon. With destructuring, we can create multiple variables from the object on a single line like so:

const {title, artist, genre} = album

This new destructuring syntax is creating individual title, artist, and genre variables, taking those specific properties from the album object.
So now if we were to console.log our newly created variables we would see:

console.log(title) // 'A Kind of Blue'
console.log(artist) // 'Miles Davis'
console.log(genre) // 'Jazz'

Destructuring is a super handy feature that can drastically improve the way you work with data in your projects or when dealing with API's. Hope this post adds some benefit to you!

Top comments (0)