ES6 –Object Property Shorthand and Destructuring

After a couple months of learning Javascript, I faced this situation: I can’t read some code or don’t understand it. There are so many shorthands, and it let newbies harder to understand/read it.

Object Property Shorthand

In ES6, if the object key and the value variable has the same name, we can use shorthand like this:

const name = 'Ken'
const age = 29
const user = {
    name,   //origin--> name:name
    age,    //origin--> age:age
    location:'Tokyo'
}

Destructuring

const product = {
    label: 'Red notebook',
    price: 3,
    stock: 201,
    salePrice: undefined,
    rating: 4.2
}

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

If we have an object product as above, then we assign the key-value of this object to new variables. The old way is like the code above, we use Object.KeyName.

Here is the destructuring comes to play.

As per the code below, the destructuring syntax–>const {key1, key2} = ObjectName.

const {label:productLabel, stock, rating = 5} = product

We can also decide our variable name –> const {Key1:NewVariableName, Key2, Key3, …} = ObjectName.

Also, the default (rating=5) would not affect if there is a rating key in the object.

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

transaction('order', product)

Lastly, as the example above, we can also de-structure the argument in advance inside a function definition if we knew the second argument would be passed in an object.

Leave a Comment

Your email address will not be published. Required fields are marked *

RSS
Follow by Email
LinkedIn
LinkedIn
Share