Halloween Sale
--
Days
--
Hours
--
Minutes
--
Seconds
Book a call
Halloween Sale
--
Days
--
Hours
--
Minutes
--
Seconds
Book a call
All articles

Lexical Scope in JavaScript

Metana Editorial 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.

You may also like

Angular in 2025Front-End

Angular in 2025- Still Relevant?

Yes. Angular isn't dead. Despite the React hype train and Vue's rising popularity, Angular continues to power over 360,000 websites globally according to BuiltWith's 2025 data. But here's what's really happening: you're

Metana EditorialAugust 29, 2025Read
Full-Stack

Full Stack Developer Resume Key Points You Need to Know

In today’s world, full stack developers are in high demand . However, the competitive nature of the tech industry makes securing a successful position increasingly challenging. A well-crafted full stack developer resume…

Nigel JacobNovember 28, 2024Read
Full-Stack

How to Convert a JavaScript String to Number

JavaScript is one of the most popular programming languages used today, and understanding how to work with data types is fundamental to mastering it . One of the most common tasks involves converting JavaScript string…

Metana EditorialOctober 8, 2024Read
Full-Stack

Mastering Python Exception Handling: Best Practices for Try Except

Master Python's try-except block with real examples and practical tips. Learn how to handle errors gracefully, avoid crashes, and write cleaner, more reliable code. This guide to python try exception handling covers esse

Brittni FernandoDecember 1, 2025Read
Full-Stack

What is The Hardest Subject in Software Engineering?

The software industry is evolving at a rapid pace, with emerging technologies constantly shaping the landscape. Software engineering is a vast and multidisciplinary field encompassing a wide array of topics, each…

Thinal PereraOctober 26, 2024Read
Front-End

Frontend Design Principles: Enhancing UX in Full Stack Applications

In today’s modern web development world, providing a better user experience is crucial in order to keep your users navigating your site. With users interacting with a vast array of applications daily, the quality of the…

Metana EditorialAugust 29, 2024Read
More Full-Stack articles →

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
Limited-time Halloween promo

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