Learn by reading through in order

Destructuring — Pulling Values Out of Objects and Arrays

Pull just the values you need into variables by object key name or array position, with defaults, renaming, and rest.

Want just the order number and total from an order object? Writing order.orderId and order.total over and over makes the code longer. The more fields you need, the more lines start with the same order..

This article covers destructuring, for pulling just the values you need into variables all at once, matched to key names or positions.

Pulling Out Only What You Need, by Name — Destructuring an Object

Pull the order number, total, and customer name out of a single order object, and you'd end up writing a line like const orderId = order.orderId; for every field. Repeat the same order. enough times, and it gets hard to tell at a glance which value each line is actually after.

Destructuring (syntax for pulling multiple values into variables all at once, matched to an object's key names or an array's positions) lets you write that in one line: const { orderId, total } = order;. The key names you write inside the {} on the left become the variable names as-is, and each one gets the value of the property with the matching name.

For a default when a key is missing, add it with =, as in const { shippingFee = 500 } = order;. To pull it into a variable with a different name, write const { orderId: id } = order;.

From a nested object, you can pull a value out directly with the form const { customer: { name } } = order;. What comes after the : changes the meaning depending on whether it's a variable name or curly braces.

customer: name puts customer's value into a variable called name, while customer: { name } pulls name out from inside customer. The latter never creates a variable called customer.

Destructuring Matches by Key Name
order'sorderIdMatched bythe same namevariable orderIdorder'stotalA different nameafter the :variabletotalAmountorder hasno shippingFeeAdd a= 500variable is 500
It looks for a key matching the name on the left, and that key's value gets assigned. You can change the name it lands in after the `:`, and a field with no key gets a default via `=`.
const order = {
  orderId: "ORD-1268",
  total: 12800,
  customer: { name: "Maya Chen", email: "maya@example.com" },
};

// The key names become the variable names directly
const { orderId, total } = order;
console.log(orderId);          // ORD-1268
console.log(total);            // 12800

// Add a default with = for a missing key
const { couponCode = "none" } = order;
console.log(couponCode);       // none

// Write a different variable name after the :
const { total: totalAmount } = order;
console.log(totalAmount);      // 12800

// Pull a value directly from inside a nested object
const { customer: { email } } = order;
console.log(email);            // maya@example.com

Pull just the values you need for display out of an order object, one line at a time. order is already declared.

① Pull out the order number and total together, and print them formatted as "ORD-3120 / $8600".

② Pull the customer name out directly from inside the nested object and print it.

③ Pull out the shipping fee with a default of 500, and print it. order has no shipping fee field.

④ Pull the order number into a variable called id and print it.

(If it runs correctly, an explanation will appear.)

JavaScript / TypeScript Editor

Run code to see output

Receiving by Order — Array Destructuring and rest

Arrays have no key names, so you match by the position you're pulling from. Want to handle the first item in a cart and the 2nd separately? Instead of writing cart[0] and cart[1], you can list variable names and pull both values out at once.

The syntax is const [firstItem, secondItem] = cart;. The values at index 0 and index 1 get assigned left to right. To skip over a position, just place a comma, as in const [, secondItem] = cart;.

For a position with no element, you can add a default with = "(none)". Note the default only kicks in when that position's value is undefined.

If a null is sitting there, you get null as-is. To replace null with a default too, use ??, from the previous article.

To pull everything left over out at once, use rest syntax (adding ... on the left side of a destructuring pattern to bundle every value you didn't name into a single array or object).

Write const [firstItem, ...restItems] = cart;, and restItems gets everything from the 2nd item on, as an array. ... can only go at the very end of the left side.

Arrays Are Received by Position
cart's1st itemfirstItemgets itone productcart's2nd item on...restItemsbundles themthe rest,as an arraycart hasno 5th itemAdd a= defaultthe defaultis used
They match left to right, and the name with `...` picks up everything left over, bundled as an array.
const cart = ["Wireless Mouse", "USB-C Hub", "Monitor Arm"];

// Values are assigned left to right
const [firstItem, secondItem] = cart;
console.log(firstItem);            // Wireless Mouse
console.log(secondItem);           // USB-C Hub

// A bare comma skips over that position
const [, , thirdItem] = cart;
console.log(thirdItem);            // Monitor Arm

// ... collects everything left over as an array (renamed since the 1st is already used above)
const [headItem, ...tailItems] = cart;
console.log(tailItems.join(", "));  // USB-C Hub, Monitor Arm

// Objects can bundle the rest too
const product = { name: "USB-C Hub", price: 2480, stock: 12 };
const { name, ...spec } = product;
console.log(Object.keys(spec).join(", "));  // price, stock

Split a cart's contents into the first item and everything else. cart is already declared.

① Split it into the first item and the rest, bundled into an array, then print the first item.

② Print how many items are in "the rest."

③ Pull out just the 2nd item using syntax that skips the first, and print it.

④ Pull out the 5th item using commas to skip the first 4, giving it a default of "(none)", and print it.

JavaScript / TypeScript Editor

Run code to see output

Split a product object into the field used for display and everything else. product is already declared.

① Pull out just the product name, splitting the rest into a separate object, then print the name.

② Print the keys of the object bundling the rest, joined with ", ".

③ Pull out the stock count with a default of 0 for when the key is missing, and print it.

JavaScript / TypeScript Editor

Run code to see output
QUIZ

Knowledge Check

Answer each question one by one.

Q1Write const { total: amount } = order;. Which variable gets created?

Q2With const [, second = "(none)"] = ["A"];, what ends up in second?

Q3With const [first, ...rest] = ["A", "B", "C"];, what ends up in rest?