JavaScript Destructuring
Extract values from arrays and objects into concise variables
Overview
Destructuring unpacks values from arrays or properties from objects into distinct variables. It appears in function parameters, imports, and assignments—reducing repetitive dot notation.
Syntax / Usage
// Array destructuring
const [a, b, ...rest] = [1, 2, 3, 4]
// a=1, b=2, rest=[3,4]
// Skip elements
const [, second] = ['x', 'y', 'z']
// Object destructuring
const { name, age } = { name: 'Ada', age: 36 }
// Rename
const { name: userName } = user
// Defaults
const { role = 'guest' } = user
// Nested
const { address: { city } } = profile
// Function parameters
function printUser({ name, email }) {
console.log(name, email)
}
Examples
Swap variables:
let x = 1, y = 2;
[x, y] = [y, x]
Extract React hook return values:
const [count, setCount] = useState(0)
const { user, logout } = useAuth()
Common Mistakes
- Destructuring
undefinedornullthrows—provide defaults on the pattern - Deep destructuring without defaults when nested data may be missing
- Over-destructuring obscures which fields a function actually uses
- Confusing rest in objects
{...rest}with spread in literals
See Also
spread-rest objects arrays functions