TIL Object Destructuring
POSTED ON:
TAGS: js
Object Destructuring -- something you'll see a lot in React & Vue.
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
Also objects too!
const user = {
name: 'The Wizard',
power: 100,
weapon: 'staff',
spell: 'fireball fireball fireball'
health: 'glass cannon'
};
We can directly get the variables for the object’s properties using the following syntax:
const { name, power, weapon, spell } = user;
console.log(name); // The Wizard
console.log(power); // 100
console.log(weapon); // staff
console.log(spell); // fireball fireball fireball
REFERENCE:
Via
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
and
https://medium.com/developers-arena/some-simple-and-amazing-javascript-tricks-292e1962b1f6
Related TILs
Tagged: js