1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Destructuring Explained: Objects, Arrays, Defaults and Common Errors

Destructuring pulls values out of objects and arrays into variables in a single line. Here is every pattern you will meet in real code, plus the errors that trip people up, all tested in Node.js.

9 min read
JavaScript destructuring explained: objects, arrays, defaults and common errors

Key takeaways

  • Object destructuring matches by property name. Array destructuring matches by position.
  • You can rename variables, set default values, reach into nested data and collect the rest.
  • Defaults apply only when a value is undefined, not when it is null.
  • Destructuring null or undefined throws a TypeError, so guard optional data.

An API returns a user object, and you need the name, the city and the first tag. Without destructuring, that is three lines of user.something. With it, one readable line pulls out exactly what you need. Destructuring arrived in ES2015 (ES6), and it now appears everywhere from React components to Node.js route handlers.

We ran every snippet in Node.js 24, and the outputs shown are from that run. The same syntax works in all modern browsers.

What is destructuring?

Destructuring is a syntax for unpacking values from objects or arrays into separate variables. The pattern on the left of the = mirrors the shape of the data on the right. Curly braces {} mean “take properties from an object”, and square brackets [] mean “take items from an array”.

Object destructuring

const user = {
  id: 7,
  name: "Asha",
  address: { city: "Pune", pin: "411001" },
  tags: ["admin", "beta"],
};

const { name, id } = user;
console.log(name, id);   // Asha 7

The variable names must match the property names, but the order does not matter. We asked for name before id, even though id comes first in the object. A property that does not exist simply gives undefined.

Renaming and defaults

Use a colon to store a property under a different variable name, and = to give a fallback value:

const { name: fullName, role = "viewer" } = user;
console.log(fullName, role);   // Asha viewer

Read name: fullName as “take name and call it fullName“. Renaming is useful when two objects have properties with the same name, or when a property name is not a valid variable name in your context.

Here is the subtle part. A default is used only when the value is undefined:

const { role: r2 = "viewer" } = { role: null };
console.log(r2);   // null

The property existed and was null, so the default was ignored. APIs often send null for “no value”, so if you want a fallback in both cases, use the nullish coalescing operator afterwards: const role = data.role ?? "viewer".

Nested patterns

Patterns can go as deep as the data:

const { address: { city }, tags: [firstTag] } = user;
console.log(city, firstTag);   // Pune admin

This creates only city and firstTag. It does not create variables called address or tags, which surprises people the first time. Keep nesting to one or two levels; deeper patterns become harder to read than plain property access.

The rest pattern

Three dots collect everything you did not name into a new object or array:

const { id: _id, ...rest } = user;
console.log(Object.keys(rest));   // [ 'name', 'address', 'tags' ]

This is a clean way to remove a property without changing the original object. For example, you might strip a password hash before sending a user to the browser. The rest element must come last in the pattern.

Array destructuring

With arrays, position is what matters. You can skip items with empty commas, give defaults and collect the rest:

const [a, , c = "none", ...others] = [1, 2, undefined, 4, 5];
console.log(a, c, others);   // 1 none [ 4, 5 ]

The second item was skipped, the third was undefined so its default applied, and the remaining items went into others.

Swapping variables

let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);   // 2 1

No temporary variable is needed. Array destructuring also works with anything iterable, including strings, Sets and Maps, which we use in the loops section below.

Function parameters

Destructuring in a parameter list lets a function accept an options object with clear names and defaults:

function greet({ name, greeting = "Hello" } = {}) {
  return `${greeting}, ${name ?? "guest"}`;
}
console.log(greet({ name: "Ben" }), "|", greet());
// Hello, Ben | Hello, guest

The = {} at the end matters. Without it, calling greet() with no argument would try to destructure undefined and throw. Options objects like this are easier to extend than long lists of positional arguments, because callers name what they pass and can skip the rest. Our post on JavaScript closures uses the same pattern for factory functions.

Loops, entries and Maps

for (const [key, value] of Object.entries({ pen: 10, book: 250 })) {
  console.log(key, value);
}
// pen 10
// book 250

const map = new Map([["a", 1]]);
for (const [k, v] of map) console.log(k, v);   // a 1

Object.entries() returns key-value pairs as small arrays, and array destructuring unpacks each pair. The same trick works with array methods such as map and filter, as in users.map(({ name }) => name).

Computed property names

const key = "name";
const { [key]: dynamic } = user;
console.log(dynamic);   // Asha

When the property name is only known at runtime, put it in square brackets and give the variable a name with a colon.

Errors and traps

Destructuring from null or undefined throws immediately. We hit both cases:

const { z } = null;
// TypeError: Cannot destructure property 'z' of 'null' as it is null.

const { missing: { deep } } = user;
// TypeError: Cannot read properties of undefined (reading 'deep')

The second case is common with nested API data, where one level is sometimes missing. Give the nested level a default, as in const { missing: { deep } = {} } = user, or use optional chaining, user.missing?.deep, which is often clearer.

Assigning to existing variables

let n1, n2;
({ n1, n2 } = { n1: 10, n2: 20 });
console.log(n1, n2);   // 10 20

When the line starts with {, JavaScript reads it as a block of code, not a pattern. Wrapping the whole assignment in parentheses fixes it. If the previous line has no semicolon, add one before the parenthesis, or the two lines may be joined.

Tip: If a destructuring line needs a comment to explain it, split it into two or three plain lines instead. Destructuring is meant to make code easier to read, not shorter at any cost.

Destructuring and spread are not deep copies

The rest pattern and the spread operator copy only the top level. Nested objects are still shared:

const copy = { ...user };
copy.address.city = "Delhi";
console.log(user.address.city);   // Delhi

Changing the copy’s address changed the original, because both point to the same address object. For a true deep copy of plain data, use structuredClone(user), which is built into modern browsers and Node.js. This shared-reference behaviour is a frequent cause of state bugs in front-end apps.

Real-world uses

  • React props and hooks: function Card({ title, children }) and const [count, setCount] = useState(0) are both destructuring. We simulated the hook pattern with a small function, and count was 0 and setCount a function.
  • API responses: const { data, error } = await res.json(), as shown in our Fetch API guide.
  • Module imports: import { readFile } from "node:fs/promises" looks like destructuring and is used the same way, though it is technically a separate syntax.
  • Returning several values: return an object, { total, count }, and destructure it at the call site.

Destructuring in TypeScript

TypeScript adds one common trap. A colon inside a destructuring pattern means “rename”, not “type”, so this does not do what it looks like:

// Looks like a type, but renames name to a variable called string
function greet({ name: string }) { ... }

The type goes after the whole pattern instead:

function greet({ name, greeting = "Hello" }: { name: string; greeting?: string }) {
  return `${greeting}, ${name}`;
}

// Clearer with a named type
type GreetOptions = { name: string; greeting?: string };
function greet2({ name, greeting = "Hello" }: GreetOptions) { ... }

Naming the type keeps the function signature readable and lets other code reuse it. With strict mode on, TypeScript also checks that defaults match the declared types. These snippets are illustrations and were not compiled for this article; our interface vs type guide shows compiler output for similar shapes.

Final thoughts

Destructuring is one of the most useful pieces of modern JavaScript. Remember the two rules, names for objects and positions for arrays, and the two traps, defaults ignore null and destructuring null throws. Use it to make intent clear at the top of a function, and keep patterns shallow enough that a teammate can read them in one glance.

Frequently asked questions

What is destructuring in JavaScript?

It is a syntax that unpacks values from objects or arrays into variables in one statement, such as const { name } = user or const [first] = list.

What is the difference between object and array destructuring?

Object destructuring matches by property name, so order does not matter. Array destructuring matches by position, so order is everything.

Why is my default value not used?

Defaults apply only when the value is undefined. If the value is null, the default is skipped. Use the ?? operator if you need a fallback for null too.

Why do I get “Cannot destructure property of undefined”?

You tried to destructure from undefined or null. Add a default such as = {} to the parameter or nested pattern, or check the value first.

Does destructuring copy objects?

It copies values out, but nested objects are shared by reference. Use structuredClone for a deep copy of plain data.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →