# static vs. dynamic scoping

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [concepts](https://lochiwei.gitbook.io/web/browser/concepts) ⟩ [scope](https://lochiwei.gitbook.io/web/js/scope) ⟩ static vs. dynamic scoping

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

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

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

* [lexical-scope](https://lochiwei.gitbook.io/web/js/scope/lexical-scope "mention")
* [](https://lochiwei.gitbook.io/web/js/scope "mention") / [chain](https://lochiwei.gitbook.io/web/js/scope/chain "mention")
* [lexical-environment](https://lochiwei.gitbook.io/web/js/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 %}
