Pattern matching and destructuring — pulling data apart declaratively
Manually indexing into an array or reaching into an object field by field is imperative, mechanical work — destructuring describes the SHAPE you expect the data to have and lets the language pull the pieces out for you.
Beginner
2 min read
Naming pieces of a structure instead of indexing into it
const point = { x: 10, y: 20 };// Manual, imperative accessconst x1 = point.x;const y1 = point.y;// Destructuring: describe the shape, get the names bound automaticallyconst { x, y } = point;const coords = [10, 20, 30];const [first, second] = coords; // first = 10, second = 20
Both approaches get the same values — but destructuring states the shape
being expected (an object with x and y; an array with at least two
elements) directly in the syntax, rather than a sequence of manual .field
or [index] lookups.
Destructuring function arguments directly
// Without destructuringfunction printUser(user) { console.log(user.name, user.age);}// With destructuring — the shape you need is visible right in the signaturefunction printUser({ name, age }) { console.log(name, age);}
The second version documents, right in the function signature, exactly
which fields of user this function actually cares about — a form of
self-documentation the first version doesn't provide at a glance.
Pattern matching: destructuring plus a decision
Some languages take this further with true pattern matching — not just
extracting fields, but choosing behavior based on a value's shape:
// A simplified version of the Result type from the algebraic data types lessonfunction handleResult(result) { switch (result.type) { case "ok": { const { value } = result; return `Success: ${value}`; } case "error": { const { message } = result; return `Failed: ${message}`; } }}
Languages with dedicated pattern-matching syntax (Rust's match, Python's
match statement) can check a value's shape and destructure it in one
expression, making this Result-handling pattern from the algebraic data
types lesson read even more directly as "here's what to do for each
possible shape this value could have."
Why this matters day to day
Destructuring isn't just shorter syntax — it shifts how you read code from
"trace through manual field access to figure out what's used" to "read the
shape declared right at the point of use." Combined with the algebraic data
types and Option/Result patterns from earlier in this domain, pattern
matching on a value's shape is what makes handling "this could be one of a
few different cases" feel like a natural, declarative decision rather than
a chain of manual if (result.type === "ok") checks.