Sobes.tech
Middle

Tell me about the mechanism of variable lookup in JavaScript (scope chain / lexical environment)

sobes.tech AI

Answer from AI

In JavaScript, variable lookup occurs through a scope chain, which is formed by the lexical environment.

Lexical environment is a structure that contains bindings of identifiers (variables, functions) to their values and a reference to an outer lexical environment.

When the interpreter encounters a variable reference, it first searches for it in the current lexical environment. If not found, the search continues in the outer environment, and so on, until it reaches the global environment. If the variable is not found anywhere, an error occurs.

Example:

function outer() {
  let a = 1;
  function inner() {
    let b = 2;
    console.log(a + b); // looks for b in inner, a in outer
  }
  inner();
}
outer();

Here, inner has access to its variable b and to the variable a from the outer environment outer thanks to the scope chain.

Tell me about the mechanism of variable lookup in… - sobes.tech