# object destructuring

[JS](/web/js.md) ⟩ [operator](/web/js/grammar/op.md) ⟩ [assignment](/web/js/grammar/op/assign.md) ⟩ [destructuring](/web/js/grammar/op/assign/destruct.md) ⟩ object

{% hint style="success" %}

```javascript
let opts = { title: "Menu", width: 100, height: 200};

// ⭐ object destructuring
let {title, width, noSuchThing} = opts;     // noSuchThing = undefined❗

// ⭐ rename variables
let {title: t, width: w} = opts;            // t = "Menu", w = 100

// ⭐ default values (could be function values❗)
let {width: w2 = 100, title: t2} = opts;    // t2 = "Menu", w2 = 100

// ⭐ the "rest" object
let {title: t3, ...rest} = opts;            // rest = {width: 100, height: 200}
```

:point\_right: [replit](https://replit.com/@pegasusroe/JS-object-destructuring#index.js)
{% endhint %}

{% tabs %}
{% tab title="🧨 雷區" %}

* replit ⟩ [object destructuring ⟩ catch](https://replit.com/@pegasusroe/JS-object-destructuring-catch#index.js)
* [codepen](https://codepen.io/lochiwei/pen/ExQwXEJ)

```javascript
// ⭐️ 可先宣告變數，再 destructuring，但要「小心」❗
let t, w, h;

// ------------------ 🧨 there's a catch❗ --------------------
// ⛔ SyntaxError: Unexpected token '='
//  {t, w, h} = opts;
//  ^^^^^^^^^ <------------ JS sees this as a "code block"❗
// ------------------------------------------------------------

// ✅ wrap it in "parentheses", now it's OK.
    ({title: t, width: w, height: h} = opts);
//  ^                              ^
```

{% endtab %}

{% tab title="👥 相關" %}

* [nested destructuring](/web/js/grammar/op/assign/destruct/nested.md)
* can be applied to destructure [destructuring arguments](/web/js/grammar/op/assign/destruct/args.md).
* [default parameter](/web/js/val/func/param/default-parameter.md)
  {% endtab %}

{% tab title="📗 參考" %}

* [x] JS.info ⟩ [object destructuring](https://javascript.info/destructuring-assignment#object-destructuring)
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/grammar/op/assign/destruct/obj.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
