> 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/concept/execution-context/lexical-environment/optimize.md).

# lexical environment optimizaton

🚧 under construction

[JS](/web/js.md) ⟩ [concepts](/web/browser/concepts.md) ⟩ [scope](/web/js/scope.md) ⟩ [lexical environment](/web/js/concept/execution-context/lexical-environment.md) ⟩ 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](/web/js/concept/env/js-engine.md)s try to <mark style="color:yellow;">**optimize**</mark> that, if they find that an [outer variable](/web/js/concept/execution-context/lexical-environment.md) is <mark style="color:red;">**not used**</mark> – it is <mark style="color:red;">**removed**</mark>.

An important side effect in [v8](/web/js/concept/env/js-engine/v8.md) (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 %}
