Destructuring
EasyIn plain terms
Destructuring extracts values from arrays or properties from objects into variables. Syntax: const {a,b} = obj or const [x,y] = arr. Supports defaults and nested patterns.
What you need to know
- •{ a, b } = obj
- •[x, y] = arr
- •Defaults, rename, nested
Try it yourself
Copy the code below and run it in your browser console or a code editor:
// Object
const { name, age } = { name: 'Alice', age: 25 };
const { a: x, b: y } = { a: 1, b: 2 }; // rename
// Array
const [first, second] = [1, 2, 3];
const [a, , c] = [1, 2, 3]; // skip
// Defaults
const { name = 'Guest' } = {};
// Nested
const { address: { city } } = user;
// Swap
[a, b] = [b, a];Learn more
Dive deeper with these trusted resources: