Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 33 of 58

Destructuring

Unpack values from arrays and objects in one line. Learn defaults, renaming, nested patterns, rest and destructuring in function parameters.

13 minArrays and objectsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonPull values out of arrays and objects into variables with destructuring, including defaults, renaming, nested patterns and function parameters.

After this lesson you can replace several lines of const a = list[0]; const b = list[1]; with a single, readable line, and you will recognise the destructuring patterns that appear in almost every modern codebase, including React code.

Array destructuring

Without destructuring, getting items out of an array looks like this:

javascript
const rgb = [255, 128, 0];
const red = rgb[0];
const green = rgb[1];

With destructuring you describe the shape on the left of the =:

javascript
const [red, green, blue] = [255, 128, 0];
console.log(red, green, blue);   // 255 128 0

It matches by position. You can skip items with an empty slot, and collect the rest with ...:

javascript
const [first, , third] = ["a", "b", "c"];
console.log(first, third);        // a c

const [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail);          // 1 [ 2, 3, 4 ]

A default value fills in when the position is empty: const [a = 0, b = 0] = [5] gives a = 5, b = 0.

A neat use is swapping two variables:

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

If the line before starts without a semicolon, JavaScript may read the [ as indexing the previous expression. Get used to finishing statements with semicolons here.

Object destructuring

For objects the match is by name, and order does not matter:

javascript
const user = { name: "Asha", age: 25, city: "Pune" };
const { name, age } = user;
console.log(name, age);   // Asha 25

Rename a property while unpacking by adding a colon. Read { city: town } as "take city, call it town":

javascript
const { city: town } = user;
console.log(town);   // Pune

Provide defaults with =, used when the property is missing or undefined:

javascript
const { country = "Unknown" } = user;
console.log(country);   // Unknown

You can combine both: { city: town = "Nowhere" }. And use ...rest to gather the remaining properties into a new object:

javascript
const { name: n, ...others } = user;
console.log(n);        // Asha
console.log(others);   // { age: 25, city: 'Pune' }

Note that a missing name only gives undefined. It is not an error, so a typo in a pattern fails silently.

Nested patterns

Patterns can go as deep as the data does:

javascript
const order = {
  id: 7,
  customer: { name: "Ben", address: { city: "Delhi" } },
  items: ["pen", "book"],
};

const { customer: { name, address: { city } }, items: [firstItem] } = order;
console.log(name, city, firstItem);   // Ben Delhi pen

Only name, city and firstItem become variables here; customer and address are just paths. Deep patterns are compact but get hard to read quickly. If it takes you a minute to read one, split it into two steps.

If something on the path is undefined or null, destructuring throws a TypeError. A default of an empty object guards against it: const { address: { city } = {} } = customer.

In loops and function parameters

Looping over Object.entries works well with destructuring (see objects):

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const prices = { tea: 20, coffee: 35 };
  for (const [item, price] of Object.entries(prices)) {
    log(item + " costs " + price);
  }

  // An options object with defaults, unpacked right in the parameter list
  function greet({ name, greeting = "Hello", punctuation = "!" } = {}) {
    return greeting + ", " + name + punctuation;
  }
  log(greet({ name: "Asha" }));
  log(greet({ name: "Ben", greeting: "Welcome", punctuation: "." }));
</script>

Taking one options object has a real advantage over a long list of parameters. Callers name what they pass ({ name: "Asha" }) instead of remembering an order, and they can leave out anything that has a default. The = {} after the pattern lets you call greet() with no argument at all, though name would then be undefined.

This is also why you meet destructuring so often in React, where components take their props this way, and in [value, setValue] = useState(0).

Returning several values

A function can only return one value, but that value can be an array or an object, and destructuring makes it feel like returning several. Return an array when the order is natural and the caller will pick their own names, as useState does. Return an object when there are many values or the caller may want only some of them, because names are easier to read than positions.

javascript
function minMax(list) {
  return { min: Math.min(...list), max: Math.max(...list) };
}
const { max } = minMax([4, 9, 2]);
console.log(max);   // 9

Taking only max and ignoring min costs nothing. With an array return you would have to skip over unwanted positions.

When not to destructure

Destructuring is a convenience, not a rule. If you use user.name once, writing user.name is clearer than adding a line to unpack it. Reach for it when you use several properties of the same object, when it names function parameters clearly, or when it removes repeated index numbers such as row[0] and row[1].

Common mistakes

  • Using the wrong brackets. Arrays use [ ], objects use { }.
  • Starting a statement with {. { a, b } = obj; is parsed as a block. Wrap it: ({ a, b } = obj);.
  • Expecting object order to matter. Names match, positions do not.
  • Forgetting that = gives a default and : renames. They look similar and do different jobs.
  • Destructuring null or undefined, which throws. Supply a fallback such as = {}.

Exercise

Given const config = { host: "example.com", port: 8080 }, unpack host and port, give secure a default of true, and rename host to server. Then use array destructuring to swap a = "left" and b = "right".

Show one possible answer
html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const config = { host: "example.com", port: 8080 };
  const { host: server, port, secure = true } = config;
  log(server, port, secure);

  let a = "left";
  let b = "right";
  [a, b] = [b, a];
  log(a, b);
</script>

Next: methods and this.

Key points

  • Array destructuring unpacks by position: const [a, b] = list.
  • Object destructuring unpacks by name: const { name, age } = user.
  • You can set defaults with = and rename with a colon, as in { name: userName = 'guest' }.
  • A rest element (...others) collects whatever is left into an array or object.
  • Destructuring in parameters lets a function take a single options object cleanly.

Check yourself

1. What is x after const [x, y] = [10, 20]?
2. How do you read user.name into a variable called userName?
3. What is b in const { a, b = 5 } = { a: 1 }?
4. How do you swap variables x and y without a temporary variable?