> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/grammar/op/assign/destruct/obj.md).

# 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 %}
