COVID19 Lockdown Dev Log – Day 26, Object Destructuring In JavaScript

What I Worked On

Finishing up the NodeJs Weather App.

What I Learned

When extracting object properties in JavaScript you can use an ES6 feature called Object Destructuring. It’s basically a fancy way of getting hold of object properties. Let’s create an object to play around with:

const product = {
    label: 'Gameboy',
    price: 20,
    stock: 100,
    salePrice: undefined
}

Let’s say you want to store the ‘product’ object’s properties in a variable. You can do it like this:

const label = product.label
const stock = product.stock

console.log(label, stock)

This can be pretty daunting if you have to create variables for every single property. ES6 allows you to store all properties in one variable with the following syntax:

const { label, stock } = product

console.log(label, stock)

You can even rename the property that you extract from the object:

const { label:productTitle, price:normalPrice } = product

console.log(productTitle, normalPrice)

You can even create a default value for a property that doesn’t exist in the object yet:

const { rating = 5 } = product

console.log(rating)

In a function there are two ways you can destructure an object. Let’s look at the first one. Here the function argument ‘myProduct’ is considered to have the same properties as the ‘product’ object:

const transaction = (typeOfOrder, myProduct) => {
    const { label, stock } = myProduct
    console.log(typeOfOrder, label, stock)
}

transaction('purchase order', product)

The other way to do it can be done by passing the curly brace syntax, like when you want to destructure an object property into a variable, into the function argument:

const transactionTwo = (typeOfOrder, { label, stock }) => {
    console.log(typeOfOrder, label, stock)
}

transactionTwo('purchase order', product)

I wasn’t really aware about the object destructuring syntax in functions until I started seeing the syntax in my Gatsby Portfolio project 😀 A big thanks to Andrew Mead for helping me understand object destructuring better 😀

What Distracted Me During The Day

  • Phone calls from people who thought I was a doctor 😀
  • Messenger
  • New Assassin’s Creed trailer dropped on YouTube 😀

Resources