# object destructuring

[JS](../../../..) ⟩ [operator](../..) ⟩ [assignment](..) ⟩ [destructuring]() ⟩ 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](nested "mention")
* can be applied to destructure [args](args "mention").
* [default-parameter](../../../../val/func/param/default-parameter "mention")
{% endtab %}

{% tab title="📗 參考" %}
* [x] JS.info ⟩ [object destructuring](https://javascript.info/destructuring-assignment#object-destructuring)
{% endtab %}
{% endtabs %}
