Destructuring Assignment

Destructuring assignment allows you to extract values from arrays or objects and assign them to variables in a single statement.

Arrays

"Regular" way

const fruits = ["apple", "kiwi", "banana", "tomato"]
const first = fruits[0]
const second = fruits[1]

Destructuring

const fruits = ["apple", "kiwi", "banana", "tomato"]
const [first, second] = fruits

Objects

"Regular" way

const account = {
  username: "fred",
  balance: 100000,
  type: "savings"
}
const username = account.username
const balance = account.balance

Destructuring

const account = {
  username: "fred",
  balance: 100000,
  type: "savings"
}
const { username, balance } = account

Read More

Last updated