⚖️static vs. dynamic scoping
JS ⟩ concepts ⟩ scope ⟩ static vs. dynamic scoping
When resolving identifier(s),
static scope: cares the where the variable is declared. ( scopes are determined at compile-time❗)
dynamic scope: cares the when the function is invoked. ( the resolving happens at runtime❗)
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
Last updated
Was this helpful?