Destructuring

Estimated reading time: 2 minutes
  • Destructuring is a unpacking process
let num = [2,4,5];
let [a,b] = num;
console.log(a);
// 2
let num = [2,4,5];
let [a,b] = num;
[b,a] = [a,b]
console.log(a);
// 4

object shorthand

let admin = {
  user: 'kamal',
  age: 21,
  post: 'coder'
}
let {user,age,post} = admin;
console.log(user)
// kamal
let admin = {
  user: 'kamal',
  age: 21,
  post: 'coder',
  phone: {
    office: 121,
    home: 222
  }
}
let {user,age,post,phone} = admin;
console.log(phone.office);
// 121
  • alias
let admin = {
  user: 'kamal',
  age: 21,
  post: 'coder',
  phone: {
    office: 121,
    home: 222
  }
}
let {user:u, age:a, post:p, phone:phn} = admin;
console.log(u)
// kamal
  • default value
let admin = {
  user: 'kamal',
  age: 21,
  post: 'coder',
  phone: {
    office: 121,
    home: 222
  }
}
let {user:u, age:a, post:p, phone:phn, salary:s=1000} = admin;
console.log(`${u}  paid   per month $${s}`)
// kamal  paid   per month $1000
es, es6, js