Member-only story
JavaScript destructuring is a convenient way of unpacking values from arrays or properties from objects into distinct variables. This feature allows you to extract multiple elements in a concise and readable manner. Let’s explore the different ways of using destructuring in JavaScript.
Not a Medium member? Read this article here
1. Array Destructuring
Array destructuring allows you to extract values from arrays and assign them to variables.
Basic Example:
const fruits = ['Apple', 'Banana', 'Cherry'];
const [first, second, third] = fruits;
console.log(first); // "Apple"
console.log(second); // "Banana"
console.log(third); // "Cherry"
Skipping Elements
You can skip elements in the array by leaving empty slots.
const colors = ['Red', 'Green', 'Blue', 'Yellow'];
const [primary, , tertiary] = colors;
console.log(primary); // "Red"
console.log(tertiary); // "Blue"