JavaScript ยท Chapter 39 of 55
JavaScript Destructuring
Destructuring lets you unpack values from arrays or properties from objects into distinct variables in a single concise statement.
This modern syntax reduces repetitive code, especially when extracting several values from function parameters or API responses.
Array destructuring
`const [a, b] = [1, 2];` assigns a = 1 and b = 2 based on position. You can also skip elements or use default values.
Object destructuring
`const { name, age } = person;` extracts properties matching those names. You can also rename them: `const { name: n } = person;`.
Example 1 (javascript)
const [first, second] = [10, 20];
console.log(first, second);Output
10 20Array destructuring assigns by position.
Example 2 (javascript)
const person = { name: "Zoe", age: 22 };
const { name, age } = person;
console.log(name, age);Output
Zoe 22Object destructuring extracts properties by matching key names.
Key points
- Array destructuring unpacks by position.
- Object destructuring unpacks by property name.
- Default values and renaming are supported in both.
- Widely used in function parameters and imports.
๐ก Note: Destructuring function parameters, e.g. `function greet({name}) {...}`, is a very common modern pattern.
