ES6 Destructuring Like a Pro: Simplify Arrays, Objects, Function Parameters, and Nested Structures

ES6 Destructuring Like a Pro: Simplify Arrays, Objects, Function Parameters, and Nested Structures



1️⃣ What Is Destructuring in JavaScript?

Destructuring is a feature introduced in ES6 that allows you to extract values from arrays or properties from objects and assign them to variables in a clean, readable way.

It helps you avoid repetitive code like:


const person = { name: "Sam", age: 22 }; const name = person.name; const age = person.age;

With destructuring:

const { name, age } = person; console.log(name, age); // Sam 22


2️⃣ Array Destructuring: Order Matters

You can extract values from arrays based on position:

const colors = ["red", "green", "blue"]; const [first, second] = colors; console.log(first); // red

✅ Skip values:

const [, , third] = colors;
console.log(third); // blue

✅ Swap values:

let a = 1, b = 2; [a, b] = [b, a]; console.log(a, b); // 2 1

✅ Use rest with arrays:

const [head, ...tail] = [1, 2, 3, 4]; console.log(head); // 1 console.log(tail); // [2, 3, 4]


3️⃣ Object Destructuring: Keys Matter

You can destructure objects by matching property names:


const user = { id: 101, username: "sam_dev" }; const { id, username } = user; console.log(username); // sam_dev

✅ Use aliases:

const { username: name } = user; console.log(name); // sam_dev

✅ Set default values:

const { email = "Not provided" } = user; console.log(email); // Not provided

✅ Use rest with objects:

const { id, ...rest } = user; console.log(rest); // { username: "sam_dev" }


4️⃣ Nested Destructuring and Destructuring in Functions

✅ Nested objects:

const person = { name: "Sam", address: { city: "Chennai", zip: 600001 } }; const { address: { city } } = person; console.log(city); // Chennai

✅ In function parameters:

function greet({ name, age }) { console.log(`Hello ${name}, age ${age}`); } greet({ name: "Sam", age: 22 });

✅ With arrays in function params:

function sum([a, b]) { return a + b; } console.log(sum([5, 10])); // 15



5️⃣ Common Mistakes and Pro Tips

❌ Don't mix up key names in object destructuring
❌ Don't use destructuring if readability gets worse
✅ Use it in React props, API responses, config settings
✅ Combine it with default values for robust functions


function config({ theme = "light", layout = "grid" } = {}) {
console.log(theme, layout); } config(); // light grid




This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication


Previous Post Next Post