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.
Array Destructuring
Example
Values are assigned by position
Skipping Values
Default Values
Object Destructuring
Example
Values are assigned by property name
Renaming Varibales
Default Values in Objects
Nested Destructuring
Destructuring in Function Parameters
Very common in modern JavaScript
Swapping Variables Using Destructuring
No temporary variable needed
Destructuring with Rest Operator
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); // 10console.log(b); // 20console.log(c); // 30Values are assigned by position
Skipping Values
const colors = ["red", "green", "blue"];
const [first, , third] = colors;
console.log(first); // redconsole.log(third); // blueDefault Values
const arr = [5];
const [x, y = 10] = arr;
console.log(x); // 5console.log(y); // 10Object Destructuring
Example
const user = { name: "Nikhil", age: 25};
const { name, age } = user;
console.log(name); // Nikhilconsole.log(age); // 25Values are assigned by property name
Renaming Varibales
const user = { name: "JavaScript", version: "ES6"};
const { name: lang, version: ver } = user;
console.log(lang); // JavaScriptconsole.log(ver); // ES6Default Values in Objects
const user = { name: "Rahul"};
const { name, age = 18 } = user;
console.log(age); // 18Nested Destructuring
const student = { name: "Anjali", marks: { math: 90, science: 85 }};
const { marks: { math, science } } = student;
console.log(math); // 90console.log(science); // 85Destructuring 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); // 10console.log(b); // 5No temporary variable needed
Destructuring with Rest Operator
const numbers = [1, 2, 3, 4];
const [first, ...rest] = numbers;
console.log(first); // 1console.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
