Skip to main content

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.

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.

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:
  • if
  • for
  • {} blocks

How JavaScript Resolves Variables

When JavaScript looks up a variable:
  1. It checks the current lexical environment.
  2. If missing, it checks the outer environment.
  3. Continues upward until global scope is reached.
This upward traversal is the scope chain.

Simple Example

Lexical Environment Chain:

  • inner() → has c, outer = outer()
  • outer() → has b, outer = global
  • global → has a

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