โš–๏ธstatic vs. dynamic scoping

JS โŸฉ concepts โŸฉ scope โŸฉ static vs. dynamic scoping

When resolving identifier(s),

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