JavaScript wizards code quickly and clearly by using the full capacity of the language. To work fast at scale, you need to get good at destructuring — a surprisingly underused feature for flexible value assignment from arrays or objects.
Let’s shed light on this obscure yet game-changing language element to level up your skills!
Destructuring Objects
Destructuring lets us unpack object properties into distinct variables easily in one shot.
For example, say we have a settings object:
const settings = {
notifications: true,
theme: 'dark'
};
We can get the values by destructuring into variables on assignment:
const {notifications, theme} = settings;
console.log(notifications); // true
console.log(theme); // 'dark'
Nice and clean without repetitive dot notation!
Destructuring Arrays
Similarly, array elements can be destructured into individual variables:
const languages = ['JavaScript', 'Python', 'C++'];
const [first, second] = languages;
console.log(first); //…