Scope defines the accessibility and visibility of variables, functions, and objects in specified parts of code during runtime. JavaScript employs Lexical Scoping, meaning scope is determined by the physical placement of code at author time.
flowchart TD
GlobalScope["Global Scope (Window / globalThis)"] --> FunctionScope["Function Scope (Outer Function)"]
FunctionScope --> BlockScope["Block Scope (if / for block with let / const)"]
BlockScope --> ScopeLookup{"Variable Lookup Path"}
ScopeLookup -->|1. Search Local| BlockScope
ScopeLookup -->|2. Search Enclosing| FunctionScope
ScopeLookup -->|3. Search Root| GlobalScope
| Scope Level | Declared With | Accessible Where? | Lifetime |
|---|---|---|---|
| Global Scope | Declared outside any function/block. | Accessible everywhere in script module. | Application runtime duration. |
| Function Scope | Declared inside function body (var, let, const). |
Accessible only within function body. | Duration of function invocation. |
| Block Scope | Declared inside {} block (let, const). |
Accessible only inside enclosing {} block. |
Duration of block execution. |
// Demonstrating Lexical Scope, Scope Chain, and Closures
const globalAppName = "KodSolution System"; // Global Scope
function outerModule(moduleName) {
// Function Scope (Enclosing)
const moduleVersion = "1.0.0";
function innerLogger(action) {
// Inner Function Scope
// Accesses variable from own scope (action), enclosing scope (moduleName, moduleVersion), and global scope (globalAppName)
console.log(`[${globalAppName} -> ${moduleName} v${moduleVersion}]: ${action}`);
}
return innerLogger; // Returning inner function creates a Closure!
}
// Creating closure instances
const authLogger = outerModule("AuthModule");
const dbLogger = outerModule("DatabaseModule");
authLogger("User login attempt"); // Remembers moduleName: "AuthModule"
dbLogger("Connection pool established"); // Remembers moduleName: "DatabaseModule"
const and let inside {} blocks to prevent variables from leaking into outer scopes.Explain what happens when a function references a variable that does not exist in its local scope, enclosing scope, or global scope.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.