JavaScript developers love destructuring due to its simplicity and convenience in extracting data from arrays and objects. Since its introduction in ES6, destructuring keeps growing in popularity, becoming indispensable in modern coding practices. Apart from basic usage, there are lesser-known tricks worth knowing.
This article highlights advanced destructuring techniques, showing you how to squeeze maximum juice from this powerful feature.
Nested Destructuring
Most programmers know how to destructure top-level elements from arrays or objects. What if you need to drill deeper? No worries! Just follow the trail.
Given an array of objects, you can reach nested values in no time:
const todos = [
{task: 'Clean kitchen', completed: false},
{task: 'Wash dishes', completed: true},
{task: 'Do laundry', completed: false}
];
const [, {completed}] = todos;
console.log(completed); // prints 'true'.
Similarly, digging into objects is equally smooth:
const player = {
username…