Javascript Upgrade: Destructuring

J

Destructuring is a new way to get data out of objects and arrays in ES6.  Where as before you would have to assign each item from an object or array individually destructuring gives you the ability to extract multiple items at the same time.  I’ve seen it used before on imports but never investigated the rules or how it works so this was a great topic for me.

Objects

Below are various examples of destructuring values from objects.

const person = {
  name: "Shawn",
  age: 35,
  location: "Sandy Beach"
  favourites: {
    drink: "Coke"
  }
}

//You only include the keys you need
const { name, age } = person

//Nested values are just as easy

const { drink } = person.favourites

//If you don't want to keep the same key name
//renaming is easy as well

const { location:city_name } = person
// city_name = "Sandy Beach"

//You can set default values
const { something = "test" } = person
//something = "test" since person doesn't have it

 

ARRAYS

Arrays are slightly different but mostly the same.

const data = [10,100,75, 15];

const [height, width, length, weight] = data

//height = 10
//weight = 15

const csv_row = "10,100,75,15"

const [height2, width2, length2, weight2] = csv_row.split(",")

//Easy way to swap variables

[first, second] = [second, first]

Function params

Destructuring is also useful with functions allowing you to make functions that are easier to have a variety of input params, param orders, etc.

function sayName({name = "James", message="Hi, "} = {}) {
  return `${message} ${name}`;
}

const msg = sayName({name: "Shawn"});
//msg = "Hi, Shawn"

The = {} defaults to an empty object if nothing is passed in.  Useful in this case where we have all defaults but not so good if you’re missing any.

About the author

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By shawn

Other Things