Destructuring is a powerful feature in JavaScript (and TypeScript) that lets you unpack values from arrays or extract properties from objects into distinct variables.
1. Array (List) Destructuring
Basic Example
const nums = [10, 20, 30];
const [first, second] = nums;
console.log(first); // 10
console.log(second); // 20
Skipping values
const [ , , third] = nums;
console.log(third); // 30
Default values
const [a = 1, b = 2, c = 3] = [undefined, undefined];
console.log(a, b, c); // 1 2 3
2. Object Destructuring
Basic Example
const user = { name: "Alice", age: 25 };
const { name, age } = user;
console.log(name); // "Alice"
console.log(age); // 25
Renaming variables
const { name: fullName } = user;
console.log(fullName); // "Alice"
Default values
const { city = "Unknown" } = user;
console.log(city); // "Unknown"
3. Nested Destructuring
const data = {
user: {
profile: {
username: "bob123",
email: "bob@example.com"
}
}
};
const {
user: {
profile: { username }
}
} = data;
console.log(username); // "bob123"
4. Destructuring in Function Parameters
With objects
function greet({ name, age }: { name: string; age: number }) {
console.log(`Hello ${name}, age ${age}`);
}
greet({ name: "Charlie", age: 30 });
With arrays
function sum([a, b]: [number, number]) {
return a + b;
}
console.log(sum([5, 7])); // 12
5. Combining with Rest (...)
Arrays
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
Objects
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(a); // 1
console.log(rest); // { b: 2, c: 3 }
Destructuring with TypeScript Types
type User = {
id: number;
name: string;
email?: string;
};
const user: User = { id: 1, name: "Dana" };
const { id, name, email = "N/A" } = user;
Top comments (0)