1. Variables, Scope & Hoisting
This guide explains JavaScript variables, scope, and hoisting with examples.Variables (var, let, const)
JavaScript provides three ways to declare variables.
| Keyword | Scope | Redeclare | Reassign | Hoisted | Notes |
|---|---|---|---|---|---|
var | Function scope | Yes | Yes | Yes (undefined) | Legacy |
let | Block scope | No | Yes | Yes (TDZ) | Modern |
const | Block scope | No | No | Yes (TDZ) | Must initialize |
var Example
let Example
const Example
Scope
JavaScript has three scopes.Global Scope
Function Scope
Block Scope
Hoisting
Hoisting moves declarations to the top of their scope.| Type | Hoisted? | Value |
|---|---|---|
var | Yes | undefined |
let | Yes | TDZ |
const | Yes | TDZ |
| Function | Yes | Fully available |
Hoisting Example
2. Closures and lexical environment
Lexical Environment
A lexical environment is a structure where variable and function identifiers are stored and resolved.It is created automatically by JavaScript whenever code is executed. A lexical environment has two parts:
Environment Record
Holds:- Variables
- Functions
- Parameters
Outer Environment Reference
A pointer to the parent lexical environment, enabling scope chaining.Lexical Environments Creation
Global Lexical Environment
Created at the start of the script.Function Lexical Environment
Created every time a function is invoked.Block Lexical Environment
Created for block-scoped declarations (let, const) inside:
iffor{}blocks
How JavaScript Resolves Variables
When JavaScript looks up a variable:- It checks the current lexical environment.
- If missing, it checks the outer environment.
- Continues upward until global scope is reached.
Simple Example
Lexical Environment Chain:
inner()→ hasc, outer =outer()outer()→ hasb, outer =globalglobal→ hasa
Summary
A lexical environment:- Stores identifiers and their values
- Exists for global, function, and block scopes
- Forms the basis of JavaScript’s scope chain
- Ensures variables are resolved using their lexical (written-in-code) position
Closures
A closure happens when:- A function remembers variables from its parent function
- Even after the parent function has returned / finished executing
- In short:
Closure = Function + Remembered Lexical Environment

