惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
小众软件
小众软件
F
Fortinet All Blogs
爱范儿
爱范儿
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
C
Check Point Blog
博客园 - 聂微东
D
Docker
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
aimingoo的专栏
aimingoo的专栏
Vercel News
Vercel News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
A
About on SuperTechFans
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog
宝玉的分享
宝玉的分享
Jina AI
Jina AI
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
JavaScript Lexical Scope, Lexical Environment, Scope Chai...
Gaurav Singh · 2026-06-26 · via DEV Community

Gaurav Singh

Most developers memorize the definitions of Lexical Scope, Lexical Environment, Scope Chain, and Closure without understanding what actually happens inside the JavaScript engine.

In this article, we'll build these concepts step by step and understand them from the engine's perspective.


What Does "Lexical" Mean?

Lexical means:

"Based on where things are written in the source code."

JavaScript determines variable access by looking at the physical location of functions in your code—not where they are called.


1. Lexical Scope

A function can access:

  • Its own variables
  • Variables from its outer scope

The scope is determined by where a function is defined, not where it is executed.

let dynamicVar = "I'm Global";

function checkScope() {
  console.log(dynamicVar);
}

function anotherFunction() {
  let dynamicVar = "I'm Local";
  checkScope(); // Function is called here
}

anotherFunction();

Output

I'm Global

Why?

Before execution begins, JavaScript analyzes the source code and decides which variables every function can access.

This rule is called Lexical (Static) Scope.

Although checkScope() is called inside anotherFunction(), it was defined in the global scope, so it only has access to the global dynamicVar.


What If JavaScript Used Dynamic Scope?

If JavaScript used Dynamic Scope (which depends on where a function is called), the output would be:

I'm Local

But JavaScript doesn't work this way.


Lexical Scope Search Path

Before execution starts, JavaScript builds a blueprint of variable accessibility by analyzing the code structure.

Think of it as answering this question:

"Which variables can each function access?"

That blueprint is called Lexical Scope.


2. Lexical Environment

A Lexical Environment is an internal object created whenever JavaScript starts executing a scope.

It stores:

  • Local variables
  • Function declarations
  • A reference to its parent lexical environment

It consists of:

  • Environment Record → Stores variables and functions
  • Outer Reference → Points to the parent lexical environment

Together, these make variable lookup possible.


Scope Chain

The Scope Chain is formed by connecting lexical environments through their Outer References.

When JavaScript can't find a variable in the current scope, it walks up this chain until it either finds the variable or reaches the global scope.


Easy Way to Remember

Lexical Scope is the rule that defines what a function can access.

Lexical Environment is the place where those variables are actually stored.


Interview Definition

Lexical Scope defines what a function can access, while the Lexical Environment stores those variables and maintains the relationship between parent and child scopes.


Example

const globalVar = "I am Global";

function outerFunction() {
  const outerVar = "I am Outer";

  function innerFunction() {
    const innerVar = "I am Local";

    console.log(innerVar);
    console.log(outerVar);
    console.log(globalVar);
  }

  innerFunction();
}

outerFunction();

Output

I am Local
I am Outer
I am Global


What Happens Behind the Scenes?

When innerFunction() starts executing:

JavaScript creates a brand new Lexical Environment.

It contains:

Lexical Environment (innerFunction)

Environment Record
------------------
innerVar

Outer Reference
      ↓
Lexical Environment (outerFunction)

Environment Record
------------------
outerVar

Outer Reference
      ↓
Global Lexical Environment

Environment Record
------------------
globalVar

Now suppose JavaScript needs outerVar.

The lookup process becomes:

Current Scope
      ↓
Parent Scope
      ↓
Global Scope

This lookup path is called the Scope Chain.


3. Closure

A Closure is formed when a function remembers and retains access to its outer lexical environment even after the outer function has finished execution.


In My Style

When we return an inner function, pass it as a callback, or store it in a variable, and it carries its lexical environment along with it, that is called a Closure.


Example

function outerFunction() {
  let a = 10;

  function innerFunction() {
    a++;
    console.log(a);
  }

  return innerFunction;
}

const fn = outerFunction();

fn();
fn();
fn();

Output

11
12
13


Why Doesn't a Disappear?

Normally, when outerFunction() finishes execution, its execution context is removed from the call stack.

But JavaScript notices that innerFunction still needs a.

Instead of destroying that memory, JavaScript keeps the lexical environment alive.

The returned function holds a hidden reference to it.

This preserved relationship is called a Closure.


One Snap > 100 Closure Definitions 📸

Someone asks:

"Where is the closure?"

Open Chrome DevTools:

console.dir(fn)

Expand:

[[Scopes]]

Closure (outerFunction)
{
    a: 13
}

There it is.

That hidden Closure object is the preserved lexical environment that keeps your variables alive even after the outer function has returned.


Final One-Line Difference

Concept Meaning
Lexical Scope Defines what a function can access.
Lexical Environment Stores variables and references to parent scopes.
Scope Chain The path JavaScript follows to find variables.
Closure A function together with the preserved lexical environment it remembers after the outer function has finished execution.

Key Takeaways

⟶ Lexical means where code is written.
⟶ Scope is determined during parsing, not during function calls.
⟶ Every executing scope gets its own Lexical Environment.
⟶ Lexical Environments are connected through Outer References.
⟶ Those references create the Scope Chain.
⟶ A Closure keeps a lexical environment alive as long as a function still references it.

If this article helped you understand what's happening inside the JavaScript engine, consider leaving a ❤️ and sharing it with fellow developers.

Happy Coding!