---
description: 🚧 under construction
---

# lexical environment optimizaton

[JS](../../..) ⟩ [concepts](../../../../browser/concepts) ⟩ [scope](../../../scope) ⟩ [lexical environment]() ⟩ JS engine optimization

{% hint style="warning" %}
* <mark style="color:yellow;">**in theory**</mark> while a function is alive, all outer variables are also retained.
* but <mark style="color:red;">**in practice**</mark>, [js-engine](../../env/js-engine "mention")s try to <mark style="color:yellow;">**optimize**</mark> that, if they find that an [outer variable]() is <mark style="color:red;">**not used**</mark> – it is <mark style="color:red;">**removed**</mark>.

An important side effect in [v8](../../env/js-engine/v8 "mention") (Chrome, Edge, Opera) is that <mark style="color:yellow;">**such variable**</mark> will become <mark style="color:red;">**unavailable**</mark> in <mark style="color:yellow;">**debugging**</mark>.
{% endhint %}

{% tabs %}
{% tab title="💈範例" %}
replit：[lexical environment: optimization](https://replit.com/@pegasusroe/lexical-environment-optimization#index.js)

```javascript
let value = "Surprise!";

function f() {
    
    // ⭐ `value` never used by `g`.
    // ⭐ v8 will optimize it out from the "lexical environment"!
    // ⭐ it's not accessable in the "debugger".
    let value = "the closest value";

    return function g() {
        // ⭐ in "console": type `alert(value)`.
        debugger;         // ❗ Surprise!
    }
}

let g = f();
g();
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] JS.info ⟩ [Lexical Environment](https://javascript.info/closure#real-life-optimizations) ⭐️
{% endtab %}

{% tab title="🚧 " %}
* [ ] debugging
{% endtab %}
{% endtabs %}
