Skip to content

Object destructuring in JavaScript

Object destructuring assigns the properties of an object to variables with the same names by default. Here are a few examples.

//Basic
const { user: x } = { user: 5 } // x=5

//Fail-safe
const { user: x } = { user2: 5 } //x=undefined

//Assign to new variable name
const { prop: x, prop2: y } = { prop: 5, prop2: 10 } // x=5, y=10

//Value of property
const { prop: prop, prop2: prop2 } = { prop: 5, prop2: 10 } //prop = 5, prop2=10

//Short-hand syntax
const { prop, prop2 } = { prop: 5, prop2: 10 } //prop = 5, prop2=10

//Object Rest/Spread Properties
const {a, b, ...rest} = {a:1, b:2, c:3, d:4} //a=1, b=2, rest={c:3, d:4}

Source

See also  How to get create table query preview in PHPmyadmin?

Leave a Reply

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

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