Imagine making a sandwich: you don’t pull everything out of the refrigerator, just the ingredients you need. Destructuring works the same way. When working with arrays or objects, you can extract only the items you need, making your code cleaner and more efficient.
Destructuring Arrays
Here’s the old method of assigning array items to variables:
Before
const devices = ['laptop', 'tablet', 'smartphone']; // Old way const desktop = devices[0]; const portable = devices[1]; const mobile = devices[2];
Here’s the new method using destructuring:
With Destructuring
const devices = ['laptop', 'tablet', 'smartphone']; // New way const [desktop, portable, mobile] = devices;
The order of the variables is crucial. If you only need the desktop and mobile, you can skip over the intermediate value:
const devices = ['laptop', 'tablet', 'smartphone']; const [desktop,, mobile] = devices;
Example
Destructuring is particularly useful when a function returns an array:
function compute(a, b) { const sum = a + b; const difference = a - b; const product = a * b; const quotient = a / b; return [sum, difference, product, quotient]; } const [sum, difference, product, quotient] = compute(8, 2);
Destructuring Objects
Here’s the old way of using an object within a function:
Before
const gadget = { brand: 'Apple', model: 'iPhone', type: 'mobile', year: 2022, color: 'black' }; // Old way function displayGadget(gadget) { const description = 'My ' + gadget.type + ' is a ' + gadget.color + ' ' + gadget.brand + ' ' + gadget.model + '.'; } displayGadget(gadget);
Here’s the new method with destructuring:
With Destructuring:
const gadget = { brand: 'Apple', model: 'iPhone', type: 'mobile', year: 2022, color: 'black' }; function displayGadget({type, color, brand, model}) { const description = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.'; } displayGadget(gadget);