Loading

Quipoin Menu

Learn • Practice • Grow

Destructuring is a JavaScript feature that allows you to extract values from arrays or objects and store them in variables in a clean and readable way.
Destructuring lets you unpack values from arrays or objects easily.


Why Use Destructuring?

Without destructuring:

  • Code becomes repetitive
  • Accessing properties is verbose
Destructuring helps by:
  • Writing cleaner code
  • Reducing repetition
  • Improving readability


Array Destructuring

Example

const numbers = [10, 20, 30];

const [a, b, c] = numbers;

console.log(a); // 10
console.log(b); // 20
console.log(c); // 30

Values are assigned by position


Skipping Values

const colors = ["red", "green", "blue"];

const [first, , third] = colors;

console.log(first); // red
console.log(third); // blue


Default Values

const arr = [5];

const [x, y = 10] = arr;

console.log(x); // 5
console.log(y); // 10


Object Destructuring

Example

const user = {
    name: "Nikhil",
    age: 25
};

const { name, age } = user;

console.log(name); // Nikhil
console.log(age); // 25

Values are assigned by property name


Renaming Varibales

const user = {
    name: "JavaScript",
    version: "ES6"
};

const { name: lang, version: ver } = user;

console.log(lang); // JavaScript
console.log(ver);  // ES6


Default Values in Objects

const user = {
    name: "Rahul"
};

const { name, age = 18 } = user;

console.log(age); // 18


Nested Destructuring

const student = {
    name: "Anjali",
    marks: {
        math: 90,
        science: 85
    }
};

const { marks: { math, science } } = student;

console.log(math);    // 90
console.log(science); // 85


Destructuring in Function Parameters

function showUser({ name, age }) {
    console.log(name, age);
}

showUser({ name: "Amit", age: 22 });

Very common in modern JavaScript


Swapping Variables Using Destructuring

let a = 5;
let b = 10;

[a, b] = [b, a];

console.log(a); // 10
console.log(b); // 5

No temporary variable needed


Destructuring with Rest Operator

const numbers = [1, 2, 3, 4];

const [first, ...rest] = numbers;

console.log(first); // 1
console.log(rest);  // [2, 3, 4]


Two Minute Drill

  • Destructuring extracts values from arrays and objects
  • Array destructruing works by position
  • Object destructuring works by property name 
  • Default values prevent undefined errors
  • Useful in functions and modern JS code
  • Improves readability and reduces repetition