# static vs. dynamic scoping

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

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

* [static](static "mention")： 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](../compile/compile-time "mention"):exclamation:)
* [dynamic](dynamic "mention")： 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](../compile/runtime "mention"):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](static "mention")： C, Java, <mark style="color:yellow;">**JavaScript**</mark>, Python, Ruby.&#x20;
* [dynamic](dynamic "mention")： Perl.
{% endhint %}
{% endtab %}

{% tab title="👥 相關" %}
* [lexical-scope](lexical-scope "mention")
* [](<> "mention") / [chain](chain "mention")
* [lexical-environment](../concept/execution-context/lexical-environment "mention")
{% 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 %}
