Back to Explore
GuideVibeFix editorialUpdated Nov 19, 2026

Stop digging out properties one by one: destructuring assignment, explained plainly

An order is an object made of several fields, the menu is a list of dishes, and taking fields, return values, and function parameters is all destructuring work. This guide follows MDN's Destructuring assignment reference: arrays by position, objects by name, renaming and defaults, binding vs assignment patterns, the parentheses trap, rest, function parameters, and nested destructuring.

Real photo: several open cardboard boxes stacked on a wooden floor, like parcels just unpacked

First, the boundaries of this guide. The site already has a practical guide to array methods, about how to process a list you hold; a practical guide to Promises and async/await, about the ways to write code that waits for a result to come back; and a practical guide to closures and scope, about who can see a variable. This guide is about none of those. It is about one thing only: you hold an object or an array, and you want to split what is inside it into several variables in one go. Done well, destructuring cuts value-taking code in half and makes it twice as readable. The "Greenstone Cafe" used below is still the same fictional practice project: a small web tool that takes orders for a street-side cafe. This time it is about its orders, menu, and user profiles: an order is an object made of several fields, the menu is a list of dishes, and taking fields, taking return values, and taking function parameters are all destructuring work. Every operation, code sample, and number built around it was invented to explain the technique, not a real record. All syntax and behavior of destructuring comes from MDN's Destructuring assignment reference, see each article's meta information and evidence record for sources. MDN's own examples, such as the three colors red, yellow, and green, the user Jane Doe, and the Scratchpad metadata, are the documentation's examples, not real user data.

Step 1: Destructuring is packing in reverse

Writing const arr = [a, b, c] packs three values into one array; writing const [a, b, c] = arr does the reverse, splitting the array into three variables. MDN puts it plainly: destructuring uses similar syntax to a literal, but on the left-hand side of the assignment instead, performing the reverse operation of declaring an array. Objects work the same way: const obj = { a, b, c } packs, const { a, b, c } = obj unpacks, and it is equivalent to const a = obj.a, b = obj.b, c = obj.c. When the property name and the variable name differ, rename with a colon: const obj = { prop1: x, prop2: y, prop3: z }, const { prop1: x, prop2: y, prop3: z } = obj, which means const x = obj.prop1, y = obj.prop2, z = obj.prop3. MDN adds that this capability is similar to features present in languages such as Perl and Python, so it is not a JavaScript invention. The cafe's orders are split this way: an order object holds a dish name, a count, and a price, and one line, const { dish, count, price } = order, takes them all out, instead of three lines of order.dish, order.count, and order.price. Remember the first sentence: literals pack, destructuring unpacks, and the shapes on both sides have to match.

Step 2: Array destructuring matches by position; extra variables are undefined

Array destructuring ignores names and matches by position only. MDN's example is: const foo = ["one", "two", "three"], const [red, yellow, green] = foo, red is "one", yellow is "two", green is "three". The first variable takes the first element, the second takes the second, and so on. When the left side has more variables than the right side has elements, the extra variables get nothing — they are undefined. MDN's example is: const foo = ["one", "two"], const [red, yellow, green, blue] = foo, red is "one", yellow is "two", and green and blue are both undefined. The other way around, when the right side has more elements than the left side has variables, the extra elements are simply dropped and no error is thrown. The cafe's menu ranking stepped into this trap: wanting the top three dishes by sales, it wrote const [first, second, third, fourth] = topList, but only two dishes had sold that day, fourth was undefined, and the page gained a blank card. Remember the test: array destructuring knows positions, not names, so count both sides and decide where the extra side goes.

Step 3: Object destructuring matches by name, and can rename on the way

Object destructuring ignores positions and matches by name only. MDN's example is: const user = { id: 42, isVerified: true }, const { id, isVerified } = user, id is 42 and isVerified is true. A matching name is all it takes; the order of properties in the object does not matter at all. To use a different variable name, put the new name after a colon: const o = { p: 42, q: true }, const { p: foo, q: bar } = o, foo is 42 and bar is true. MDN's own words are that const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo. Renaming can carry a default value too: const { a: aa = 10, b: bb = 5 } = { a: 3 }, aa is 3 and bb is 5, because the object has no b. The cafe's user profile is read this way: the user object has a displayName, the page wants a variable called dname, and const { displayName: dname } = user does it in one line, with no take-then-rename step. Remember the test: object destructuring knows names, not positions; the left of the colon is the property name, the right is your variable name.

Step 4: Binding patterns and assignment patterns are two different spellings

Destructuring comes in two patterns, and MDN draws the line clearly. A binding pattern starts with a declaration keyword — var, let, or const — and each property is then either bound to a variable or destructured further. MDN's example is: const obj = { a: 1, b: { c: 2 } }, const { a, b: { c: d } } = obj, and only two variables are bound: a and d. Note that all variables share one declaration: if you want some variables re-assignable and others read-only, you have to destructure twice, once with const and once with let. MDN's example is: const { a } = obj, a is constant; let { b: { c: d } } = obj, d is re-assignable. An assignment pattern starts with no keyword, and what it unpacks goes to an assignment target: a variable declared beforehand, or a property of another object. MDN's example is: const numbers = [], const obj = { a: 1, b: 2 }, ({ a: numbers[0], b: numbers[1] } = obj), a and b are written into numbers[0] and numbers[1]. The reverse is not valid: in a binding pattern, const { a: numbers[0], b: numbers[1] } = obj would be equivalent to const numbers[0] = obj.a, which is not legal syntax at all. One more rule: assignment patterns can only appear on the left-hand side of the = operator, never with compound assignment operators such as += or *=. The cafe's order page stepped into this trap: wanting to write two order fields straight into an existing array, it wrapped them in a const pattern, and the editor flagged it red at once. Remember the test: declare new variables with a binding pattern, write into existing places with an assignment pattern — the two spellings do not swap.

Step 5: Without parentheses, an object assignment falls apart

This is the most famous trap in destructuring, and MDN flags it in bold: when using object literal destructuring assignment without a declaration, the parentheses are required. Writing { a, b } = { a: 1, b: 2 } as a stand-alone statement is not valid syntax, because the { a, b } at the start of the line is read as a block, not an object literal. The correct spelling is ({ a, b } = { a: 1, b: 2 }), and once wrapped in parentheses the meaning is clear; const { a, b } = { a: 1, b: 2 } needs no parentheses, because the const at the start already says this is not a block. There is a knock-on trap: if your style leaves out trailing semicolons, the parenthesized expression needs a semicolon before it, or it may be read as calling a function on the previous line. The cafe's order page stepped into this trap: an assignment with no semicolon in front of it was joined to the line above, the variable above was executed as a function, and the page crashed. Remember the test: in object assignment destructuring, always wrap the braces in parentheses; in a no-semicolon style, add one more semicolon before the parentheses.

Step 6: Defaults rescue undefined, not null

Every destructured property can carry a default value, written as = default after the variable name. When it applies is stated strictly by MDN: the default is used when the property is not present, or has value undefined; it is not used if the property has value null. MDN's examples are: const [a = 1] = [], a is 1; const { b = 2 } = { b: undefined }, b is 2; const { c = 2 } = { c: null }, c is null, not 2. In other words, a default rescues "not given" and "given as undefined", but not "given as null". A default value can be any expression, and it is only evaluated when necessary. MDN's example is: const { b = console.log("hey") } = { b: 2 }, which logs nothing, because b already has a value and there is no need to evaluate the default. The cafe's menu items stepped into this trap: the discount field the backend returns is sometimes null, the frontend wrote const { discount = 0 } = dish expecting a safety net, and null stayed as it was, so the price came out as NaN. Remember the test: defaults cover undefined, not null; for a field the backend may return as null, check for null first, then talk about defaults.

Step 7: Rest always goes last, and what you get is a new container

A destructuring pattern can end with a rest property, written ...rest. In array destructuring it collects the remaining elements into a new array; in object destructuring it copies all enumerable own properties not already picked off by the pattern into a new object. MDN's examples are: const { a, ...others } = { a: 1, b: 2, c: 3 }, others is { b: 2, c: 3 }; const [first, ...others2] = [1, 2, 3], others2 is [2, 3]. Two iron rules: the rest property must be the last in the pattern, and must not have a trailing comma. MDN's example is: const [a, ...b,] = [1, 2, 3] throws a SyntaxError: rest element may not have a trailing comma. One more thing that is easy to misunderstand: the container rest builds is new, but if its members are themselves objects, the references are still the original ones — the language does no implicit deep copying. MDN's own words are that there is no implicit deep-copying: the rest property creates a new object (or array), but all its member values, if they are object references, remain the same. Array rest can even hold another binding pattern: const [a, b, ...{ pop, push }] = array pulls pop and push off the collected remainder array; const [a, b, ...[c, d]] = array keeps splitting by position. Objects cannot do that: const { a, ...{ b } } = { a: 1, b: 2 } throws, because object rest must be followed by an identifier only. The cafe's order filtering is written this way: const { id, ...rest } = order, id is taken aside on its own, and rest is the remaining fields with id removed, passed straight to the next component. Remember the test: rest always goes last, with no comma after it; what it gives you is a new container, not a deep copy.

Step 8: Swap two variables with no temporary variable

Without destructuring, swapping two variables needs a temporary variable in the middle: temp = a, a = b, b = temp, three lines of code. Destructuring does it in one line. MDN's example is: let a = 1, let b = 3, [a, b] = [b, a], a becomes 3 and b becomes 1. The right-hand [b, a] is first evaluated into a new array [3, 1], and the left-hand [a, b] then splits it back by position, so the swap is done. Two elements inside an array can swap the same way: const arr = [1, 2, 3], [arr[2], arr[1]] = [arr[1], arr[2]], and arr becomes [1, 3, 2]. Note that this uses the assignment pattern: a, b, and arr were all declared beforehand, and there is no const on the left, so this is an assignment, not a declaration. The cafe's menu sorting uses exactly this trick: when a user taps "move up", the current dish swaps with the one above it in one line, [menu[i], menu[i - 1]] = [menu[i - 1], menu[i]], with no temporary variable and no splice. Remember the test: to swap two values, build a new array on the right first, then split it back by position on the left, all in one line.

Step 9: A function that returns an array splits open in one line; skip what you do not want with commas

When a function returns an array, destructuring makes taking the return value much shorter. MDN's example is: function f() { return [1, 2]; }, const [a, b] = f(), a is 1 and b is 2. Return values you do not want can be skipped with an empty comma: function f() { return [1, 2, 3]; }, const [a, , b] = f(), a is 1 and b is 3, with the 2 in the middle unwanted; const [c] = f(), c is 1, taking only the first. You can even skip them all with [, ,] = f(), although MDN notes that in this case it is probably clearer to just call the function and not use destructuring at all, since the return value is not used by anyone. The cafe's regular-expression parsing is written this way: in MDN's parseProtocol example, the array exec returns starts with the full match followed by the groups, and const [, protocol, fullHost, fullPath] = parsedURL skips the full match with one leading comma, so protocol takes "https" directly. Remember the test: split return values by position, leave an empty comma for the ones you do not want; if you want none of them, do not destructure — just call.

Step 10: Function parameters can be destructured too, and defaults must be complete

An object passed as a function parameter can be unpacked right in the parameter list. MDN's example uses a user object: const user = { id: 42, displayName: "jdoe", fullName: { firstName: "Jane", lastName: "Doe" } }. Taking only id: function userId({ id }) { return id; }, userId(user) returns 42. Renaming works too: function userDisplayName({ displayName: dname }) { return dname; }, userDisplayName(user) returns "jdoe". Nesting can be unpacked as well: function whois({ displayName, fullName: { firstName: name } }) { return `${displayName} is ${name}`; }, whois(user) returns "jdoe is Jane". Parameters can also carry defaults: MDN's drawChart example is function drawChart({ size = "big", coords = { x: 0, y: 0 }, radius = 25 } = {}), called with { coords: { x: 18, y: 30 }, radius: 30 }, size falls back to "big". The key is the = {} at the end of the parameter: it is the default value of the whole destructured pattern. MDN states it plainly: without it, the function looks for at least one argument to be supplied when invoked; with it, you can call drawChart() without supplying any parameters. The cafe's order-rendering function stepped into this trap: function renderOrder({ dish, count } = {}) was written as function renderOrder({ dish, count }), and a place on the home page called it with no argument at all, so the page threw. Remember the test: parameter destructuring always pairs with = {}; defaults live on two levels — one for each property, one for the whole object.

Step 11: Nested splits, splits inside loops, arrays and objects mixed

Destructuring can nest layer inside layer, down to exactly the level you want. MDN's metadata example is: const metadata = { title: "Scratchpad", translations: [{ locale: "de", title: "JavaScript-Umgebung", url: "/de/docs/Tools/Scratchpad" }], url: "/en-US/docs/Tools/Scratchpad" }, const { title: englishTitle, translations: [{ title: localeTitle }] } = metadata, englishTitle is "Scratchpad" and localeTitle is "JavaScript-Umgebung". Note that the translations array in the middle and the object inside it are not bound as variables themselves; only the two renamed names at the deepest level are bound. Loop variables can be destructured too: MDN's example has a people array where each person has a name and a family, for (const { name: n, family: { father: f } } of people), printing "Name: Mike Smith, Father: Harry Smith" directly. Arrays and objects can also be mixed: MDN's example is const props = [{ id: 1, name: "Fizz" }, { id: 2, name: "Buzz" }, { id: 3, name: "FizzBuzz" }], const [, , { name }] = props, the first two commas skip the first two items, the third item yields its name, giving "FizzBuzz". The cafe's order-list rendering is written this way: for (const { dish, count } of orders), the loop variable is split at once, dish and count are ready to use, and the loop body never writes order.dish again. Remember the test: nested destructuring binds only the innermost names, the middle layers are just passing through; split the loop variable and the loop body stays clean.

Step 12: Computed property names and hyphenated property names

A property name is not always a hard-coded literal; it may be a string sitting in a variable. MDN's example is: const key = "z", const { [key]: foo } = { z: "bar" }, foo is "bar". The [key] in brackets is evaluated to "z" first, and the property is then taken by that name. Some property names are not valid JavaScript identifiers at all, such as "fizz-buzz" with a hyphen. MDN's example is: const foo = { "fizz-buzz": true }, const { "fizz-buzz": fizzBuzz } = foo, fizzBuzz is true. Quotes plus a colon do it: the original property name goes in quotes on the left, a legal variable name goes on the right of the colon, and the problem is worked around. The cafe's dish data stepped into this trap: the backend returns a field named "spicy-level", the frontend wrote const { spicy-level } = dish directly, the editor flagged it red, and const { "spicy-level": spicyLevel } = dish fixed it. Remember the test: when the property name lives in a variable, compute it with square brackets; when it is not a legal identifier, rename it with quotes and a colon.

Step 13: Array destructuring follows the iterable protocol; object destructuring searches up the prototype chain

The right-hand side of array destructuring does not have to be an array; any iterable will do. MDN's example is: const [a, b] = new Map([[1, 2], [3, 4]]), a is [1, 2] and b is [3, 4]. A non-iterable cannot be destructured as an array: const obj = { 0: "a", 1: "b", length: 2 }, const [a, b] = obj throws a TypeError: obj is not iterable — looking like an array is not the same as being iterable, and the array-like objects from the array methods guide cannot be split here either. One more detail: an iterable is only iterated until all bindings are assigned. In MDN's generator example, an iterable that logs a number each time it yields one, const [a, b] = obj logs only 0 and 1; but const [a, b, ...rest] = obj logs 0, 1, 2, and 3, because rest has to collect everything that remains. Object destructuring looks up differently: if a property is not on the object itself, the search continues up the prototype chain. MDN's example is: const obj = { self: "123", __proto__: { prot: "456" } }, const { self, prot } = obj, self is "123" and prot is "456". Finally, two red lines: destructuring null or undefined throws a TypeError — const { a } = undefined throws, const { b } = null throws, and even the empty pattern const {} = null throws; but destructuring a primitive does not throw, because the value is wrapped into its wrapper object first and the property is read from that wrapper — in const { a, toFixed } = 1, a is undefined and toFixed is the number's method. The cafe's order-detail page stepped into this trap: before the order had loaded it was null, the page ran const { dish } = order on first paint, and the screen went blank. Remember the test: for array destructuring ask "can it be iterated", for object destructuring ask "is it null"; a property on the prototype chain is found by destructuring just the same.

Step 14: 90 destructuring incidents in one month — check yourself against the chart

Bar chart of 90 destructuring-related incidents in one month in the fictional Greenstone Cafe project, by cause

The chart above shows a fictional month for the Greenstone Cafe project: 90 incidents related to destructuring in total. Forgetting the parentheses, so an object assignment was read as a code block: 27, or 30.0%, the largest group; defaults that only rescue undefined, not null, so null stayed as it was: 18, or 20.0%; rest not placed last, or given a trailing comma: 18, or 20.0%; destructured function parameters with no default empty object, so a call with no argument threw: 15, or 16.7%; destructuring null or undefined, which throws outright: 12, or 13.3%. 27 + 18 + 18 + 15 + 12 = 90, and the books balance. These numbers are invented examples, meant to show at a glance that the first group is nearly a third — and that its root cause is only one thing: the parentheses in object assignment destructuring are not optional, they are part of the syntax.

Checklist: after writing code with destructuring, tick each item

First, literals pack and destructuring unpacks; arrays match by position, objects by name, and the shapes on both sides must line up. Second, extra array variables are undefined and extra object properties are dropped — count both sides. Third, rename with a colon, the left of the colon is the property name and the right is your variable name, and renaming can carry a default value. Fourth, declare new variables with a binding pattern and write into existing places with an assignment pattern; a mixed spelling like const { a: numbers[0] } is invalid. Fifth, always add parentheses to object assignment destructuring; in a no-semicolon style, add one more semicolon before the parentheses. Sixth, defaults rescue undefined, not null — check a null field for null before talking about defaults; a default is only evaluated when needed. Seventh, rest always goes last, with no comma after it; what it gives you is a new container, not a deep copy. Eighth, to swap two values, build a new array on the right first, then split it back by position on the left. Ninth, split function return values by position, leave an empty comma for the ones you do not want, and do not destructure at all if you want none of them. Tenth, parameter destructuring always pairs with = {}, with defaults on both levels — one for each property, one for the whole object. Eleventh, nested destructuring binds only the innermost names; split the loop variable and the loop body stays clean. Twelfth, compute a property name held in a variable with square brackets, and rename a hyphenated property name with quotes and a colon. Thirteenth, for array destructuring ask "can it be iterated", for object destructuring ask "is it null"; a property on the prototype chain is found by destructuring just the same. If any item cannot be answered, go back to its section and read it again — that is worth more than memorizing ten more APIs.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: a bank of light gray metal filing cabinets with one drawer pulled open, revealing rows of hanging file folders inside
Guide
A real database inside the browser: IndexedDB local storage, explained plainly

localStorage only stores strings and has no indexes. IndexedDB is a real database in the browser: structured data, far larger capacity, indexes, and transactions. Following MDN's Using IndexedDB, IDBDatabase, and IDBObjectStore: the five-step routine, opening, upgrades, keys, indexes, transactions, add versus put, get, cursors, ranges, and multi-tab upgrades.

Tool TipsData WorkflowsFrontend Engineering
Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a laptop, tablet, and phone on a wooden table showing the same green-leaf website, the phone view with navigation in one column, a potted plant nearby
Guide
Squashed on phones? Responsive layout and media queries, explained plainly

One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.

Mobile AppsDesign ExperienceFrontend Engineering