Learn how nested functions search outwards through the Lexical Scope Chain to locate variables in parent scopes.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
Scope determines where variables are accessible in your code. Lexical Environment refers to where code is physically written in your script hierarchy.
When a function accesses a variable, JavaScript searches its local scope first. If not found, it travels UP the Scope Chain to parent scopes until it reaches the Global Scope.
Outer scopes cannot look inside inner function scopes, but inner functions have full access to their parent lexical environments:
[ Global Scope ] -> globalVar = "Global"
^
| (Searches Upward)
[ Outer Function ] -> outerVar = "Outer Scope"
^
| (Searches Upward)
[ Inner Function ] -> localVar = "Local"
const globalName = "DevLoom";
function outer() {
const outerVar = "Outer Scope";
function inner() {
// Searches local -> Outer -> Global
console.log(`${globalName} | ${outerVar}`);
}
inner();
}
outer(); // Output: "DevLoom | Outer Scope"
JavaScript uses Lexical Scoping (Static Scoping). This means variable resolution depends on where functions are defined in the source code, NOT where they are called from!
const, let, or var inside a function (e.g. score = 100) implicitly attaches it to the global window object in non-strict mode.Keep variables tightly scoped inside functions. Next, let's explore Block Scope and the Temporal Dead Zone (TDZ)!