Skip to main content

Scope

A variable declared with var can be access outside it's block scope (not global scope) but not outside of functions local scope.

Lexical Scope

It determines how variable names are resolved in nested functions which is by their position within the source code, specifically where they are declared within the nested scopes (such as functions or blocks).

  • Functions are lexically scoped, meaning they “remember” the scope in which they were created.
  • This leads to closures.
function outer() {
let outerVar = "I am outer";

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

inner();
}

outer(); // Output: I am outer

Variable Shadowing

If a variable in the inner scope has the same name as one in the outer scope, it “shadows” the outer one.

let name = "Global";

function showName() {
let name = "Local"; // shadows global variable
console.log(name);
}

showName(); // Local
console.log(name); // Global

Scope Chain

When you use a variable, JavaScript looks for it:

  1. In the current scope
  2. If not found, in the outer scope
  3. Keeps going up until global scope
  4. If still not found → ReferenceError
let globalVar = "Global";

function outer() {
let outerVar = "Outer";

function inner() {
let innerVar = "Inner";
console.log(innerVar); // Inner
console.log(outerVar); // Outer
console.log(globalVar); // Global
}

inner();
let globalVar = "Global";

function outer() {
let outerVar = "Outer";

function inner() {
let innerVar = "Inner";
console.log(innerVar); // Inner
console.log(outerVar); // Outer
console.log(globalVar); // Global
}

inner();
}

outer();