Summer 20% off--:--:--
Book a call

Summer 20% off

--:--:--
Book a call
All articles
Full-Stack

Lexical Scope in JavaScript

Metana Editorial March 3, 2025 4 min read
Lexical Scope in JavaScript

When writing JavaScript, variable accessibility is determined by where a function is defined. This behavior is called lexical scoping. JavaScript follows a lexical scope model, meaning it resolves variable lookups based on where the function was declared in the source code, not where it is executed.

Why Should You Care?

Understanding lexical scope is essential because:

  • It prevents unintended variable access issues.
  • It helps in writing modular and reusable code.
  • It is the foundation of closures, one of JavaScript’s most powerful features.

What is Lexical Scope in JavaScript?

Lexical Scope vs. Dynamic Scope

Before diving deep, let’s differentiate lexical scope from dynamic scope:

FeatureLexical ScopeDynamic Scope
DefinitionScope is determined at the time of function declarationScope is determined at the time of function execution
Where Used?JavaScript, PythonSome old languages like Bash, Perl
How Variables are Resolved?By looking at the source code structureBy following the call stack

Since JavaScript uses lexical scoping, functions always have access to variables in the scope where they were defined, not where they are called.

How Lexical Scope Works

Lexical scope means a function remembers the environment (variables) where it was created.

Variable Lookup in JavaScript

Whenever a function accesses a variable, JavaScript follows this lookup order:

  1. Local Scope – First, the function checks its own variables.
  2. Enclosing Scope – If the variable isn’t found locally, JavaScript looks into the outer (parent) scope.
  3. Global Scope – If it’s still not found, JavaScript checks the global scope.
  4. Reference Error – If the variable isn’t found anywhere, JavaScript throws a ReferenceError.

Example: Lexical Scope in Action

function outer() {
    let outerVar = "I'm in outer!";
    
    function inner() {
        console.log(outerVar);  // Accessible due to lexical scoping
    }
    
    inner();
}
outer();
  • Output: "I'm in outer!"
  • Here, inner() has access to outerVar because of lexical scope.

Closures and Their Relationship with Lexical Scope

A closure is a function that remembers variables from its lexical scope even after execution.

Key Differences Between Lexical Scope and Closures

FeatureLexical ScopeClosures
What it does?Defines where variables are accessibleAllows functions to retain access to outer variables
When is it used?At function declarationWhen a function is returned and executed later
ExampleVariable lookup inside a functionA function “remembering” a variable

Example: Closures Retaining Lexical Scope

function counter() {
    let count = 0;  // Lexical Scope

    return function() {
        count++;  // Closure retains access
        console.log(count);
    };
}

const increment = counter();
increment(); // Output: 1
increment(); // Output: 2

Here, even after counter() finishes execution, count persists because the inner function creates a closure.

Real-World Examples of Closures in Action

Creating Private Variables (Encapsulation)

function createUser(name) {
    let password = "secret123";  // Private variable

    return {
        getName: function() {
            return name;
        },
        checkPassword: function(pass) {
            return pass === password;
        }
    };
}

const user = createUser("Alice");
console.log(user.getName());        // "Alice"
console.log(user.checkPassword("123")); // false
console.log(user.checkPassword("secret123")); // true

Event Listeners Retaining Data

function setupClickHandler(buttonId) {
    let count = 0;

    document.getElementById(buttonId).addEventListener("click", function() {
        count++;
        console.log(`Button clicked ${count} times`);
    });
}

setupClickHandler("myButton");
  • The event listener retains access to count, even though setupClickHandler has already executed.

Best Practices for Working with Scope and Closures

Minimize Global Variables

// ❌ Bad practice
var globalCount = 0;

// ✅ Good practice
function increment() {
    let count = 0;
    return function() { count++; };
}

Use let and const Instead of var

function testScope() {
    if (true) {
        let localVar = "I'm safe!";
    }
    console.log(localVar);  // ❌ ReferenceError
}

Clear Event Listeners

const btn = document.getElementById("myBtn");
function handleClick() {
    console.log("Clicked!");
}
btn.addEventListener("click", handleClick);

// ✅ Remove listener when done
btn.removeEventListener("click", handleClick);

FAQs

What is lexical scope in JavaScript?

  • Lexical scope means a function’s variables are determined by where the function is defined, not where it’s called.

How do closures work?

  • Closures allow functions to “remember” variables from their lexical scope, even after execution.

Are lexical scope and closures the same thing?

  • No. Lexical scope determines variable access, while closures “retain” variables from lexical scope even after execution.

How do I prevent closures from causing memory leaks?

  • Remove event listeners when not needed.
  • Use weak references (WeakMap).
  • Avoid unnecessary variable retention.

Share
Metana Editorial

Written by

Metana Editorial

Powered by Metana Editorial Team, our content explores technology, education and innovation. As a team, we strive to provide everything from step-by-step guides to thought provoking insights, so that our readers can gain impeccable knowledge on emerging trends and new skills to confidently build their career. While our articles cover a variety of topics, we are highly focused on Web3, Blockchain, Solidity, Full stack, AI and Cybersecurity. These articles are written, reviewed and thoroughly vetted by our team of subject matter experts, instructors and career coaches.

Talk to an advisor

Book a call with a real human before the next cohort fills.

Speak with an advisor. We'll map the right program to your goals - and lock in your enrollment offer.

20% off enrollment offer

20% OFF - limited-time enrollment offer.

Applied automatically when you book a call before the timer hits zero.

--
Days
--
Hours
--
Minutes
--
Seconds
  • Guarantee: Job or 100% money back
  • Expert-curated curriculum
  • On-demand mentor support
Advisor Elena RodriguezAdvisor Sarah JenningsAdvisor David Chen
Real advisors · reply within 2 hours

Book your call

Free