> 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/scope/static-vs-dynamic.md).

# static vs. dynamic scoping

[JS](/web/js.md) ⟩ [concepts](/web/browser/concepts.md) ⟩ [scope](/web/js/scope.md) ⟩ static vs. dynamic scoping

{% hint style="success" %}
When <mark style="color:yellow;">**resolving**</mark> [identifier](/web/js/grammar/token/id.md)(s),&#x20;

* [static scope](/web/js/scope/static.md)： cares the <mark style="color:yellow;">**where**</mark> the <mark style="color:yellow;">**variable**</mark> is <mark style="color:yellow;">**declared**</mark>. \
  ( scopes are determined at [compile-time](/web/js/compile/compile-time.md):exclamation:)
* [dynamic scope](/web/js/scope/dynamic.md)： cares the <mark style="color:yellow;">**when**</mark> the <mark style="color:yellow;">**function**</mark> is <mark style="color:yellow;">**invoked.**</mark> \
  ( the resolving happens at [runtime](/web/js/compile/runtime.md):exclamation:)
  {% endhint %}

{% tabs %}
{% tab title="💈範例" %}

```javascript
const { log } = console;

let x = 10;
let y = 20;

// this function needs two variables `x`, `y` to run.
//
// ⭐ static scoping: 
//    variables are taken from lexical scopes at compile time.
//    (in this case, x = 10)
//
// ❗ dynamic scoping:
//    variables are taken at runtime when this function is called.
//    (in this case, `f` is called within `g`, at that point, x = 99)
function f() {
    log(x, y);
}

function g() {
    let x = 99;
    f();
}

g();    
// ⭐ static scope : 10, 20
// ❗ dynamic scope: 99, 20
```

{% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="info" %}

* [static scope](/web/js/scope/static.md)： C, Java, <mark style="color:yellow;">**JavaScript**</mark>, Python, Ruby.&#x20;
* [dynamic scope](/web/js/scope/dynamic.md)： Perl.
  {% endhint %}
  {% endtab %}

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

* [lexical scope](/web/js/scope/lexical-scope.md)
* [scope](/web/js/scope.md) / [scope chain](/web/js/scope/chain.md)
* [lexical environment](/web/js/concept/execution-context/lexical-environment.md)
  {% endtab %}

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

* [ ] Anil ⟩ [Scope, Lexical Environment and Scope Chain in JavaScript](https://medium.com/@anilakgunes/scope-lexical-environment-and-scope-chain-in-javascript-559aadb7dca8) ⭐️
* [ ] Wikipedia ⟩ [lexical scope vs. dynamic scope](https://en.wikipedia.org/wiki/Scope_\(computer_science\)#Lexical_scope_vs._dynamic_scope)
  {% endtab %}
  {% endtabs %}
