⚖️static vs. dynamic scoping

JSconceptsscope ⟩ 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