Destructuring in JavaScript(beginner to advance)
Source: Dev.to
Without Destructuring
const user = {
name: "John",
age: 20,
city: "Mumbai"
};
const name = user.name;
const age = user.age;
const city = user.city;
console.log(name, age, city);With Destructuring
const user = {
name: "John",
age: 20,
city: "Mumbai"
};
const { name, age, city } = user;
console.log(name, age, city);Object Destructuring
Basic Assignment
const user = { name: 'Alice', age: 25 };
const { name, age } = user; // name = 'Alice', age = 25Renaming
const user = { name: 'Alice' };
const { name: userName } = user; // userName = 'Alice'Default Values
const user = {};
const { city = 'Unknown' } = user; // city = 'Unknown'Nested Destructuring
const profile = { id: 1, info: { email: 'a@ex.com' } };
const { info: { email } } = profile; // email = 'a@ex.com'Array Destructuring
Basic Assignment
const colors = ['red', 'blue', 'green'];
const [first, second] = colors; // first = 'red', second = 'blue'Skipping Values
const colors = ['red', 'blue', 'green'];
const [first, , third] = colors; // first = 'red', third = 'green'Swapping Variables
let a = 4;
let b = 5;
[a, b] = [b, a]; // a = 5, b = 4How it works
- The right‑hand side array
[b, a]is evaluated first, producing[5, 4]. - The destructuring on the left side
[a, b] = [5, 4]then assignsa = 5andb = 4.
Rest Operator
const numbers = [1, 2, 3, 4];
const [one, ...others] = numbers; // one = 1, others = [2, 3, 4]Important Points of Destructuring
- Destructuring does not modify the original object or array; it only extracts values.
- It creates a shallow copy. Nested objects or arrays remain references to the original data.
const user = {
name: "Abhi",
address: {
city: "Jalandhar"
}
};
const { address } = user;
address.city = "Delhi";
console.log(user.address.city); // Delhi (original also changed)- Attempting to destructure
nullorundefinedthrows aTypeError.
const { name } = null; // TypeErrorConclusion
Destructuring in JavaScript (introduced in ES6) provides a concise syntax for extracting values from objects and arrays, improving readability and reducing boilerplate code. It supports renaming, default values, nested structures, the rest operator, and even enables elegant variable swapping without temporary placeholders.