Lexical Scope

Lexical scope, also known as static scope, is a concept in JavaScript (and many other programming languages) that describes how the scope of variables is determined at the time of lexing or parsing, which is before the code is executed. Lexical scope is based on the physical structure of the code, where a variable is defined.

One important characteristic of lexical scope is that it is determined by the placement of functions and blocks in the code during the parsing phase. This means that a function or block can access variables from its containing (outer) scope, but not from the scopes that contain it.

function outer() {
    var outerVar = 40;

    function inner() {
        console.log(outerVar); // inner can access outerVar
    }

    inner();
}

outer();
// console.log(outerVar); // Error: outerVar is not defined outside outer