JavaScript Array Destructuring: Positions and Defaults
Quick answer
Array destructuring binds values from an iterable to named variables. It is useful when a small ordered result has a known shape.
How it works
In const [first, , third = 0] = values, the empty position advances the iterator without binding a name. A default runs only for undefined, including when the iterator is exhausted. Null is a supplied value. Array patterns use iteration rather than arbitrary numeric properties.
const [x, , z = 7] = [2, 9];console.log(x, z);Expected output in Node.js:
2 7Skipping consumes the second value; exhaustion selects the default.
const [x = 5, y = 8] = [null, undefined];console.log(x, y);Expected output in Node.js:
null 8Only undefined selects a default.
Common mistakes
Do not assume missing and null are equivalent. Destructuring a noniterable such as a plain object fails; use an object pattern instead.
Practice
Extract the first and third coordinates, then repeat with only one coordinate.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Array Destructuring: Positions and Defaults — Knowledge Check
Apply the taught concept and predict the output.
Which source is valid for an array binding pattern?
What does a comma with no binding in an array pattern do?
When is a destructuring default evaluated?
What is the exact console output in JavaScript Array Destructuring: Positions and Defaults example 1?
const [x, , z = 7] = [2, 9];console.log(x, z);What is the exact console output in JavaScript Array Destructuring: Positions and Defaults example 2?
const [x = 5, y = 8] = [null, undefined];console.log(x, y);