logo

Variables and Scopes

How variable declarations (var, let, const) work and scope rules in JavaScript.

Short explanation

Variables store values and are declared using var, let, or const. var is function-scoped (or global), while let and const are block-scoped and prevent certain classes of bugs.

Syntax examples

var a = 1; // function-scoped
let b = 2; // block-scoped
const c = 3; // block-scoped, immutable binding

How JS handles it internally

The JavaScript engine creates bindings in lexical environments. var declarations are hoisted with an initial value of undefined, while let and const are hoisted but are in a temporal dead zone until initialized.

Diagram

diagram-placeholder

Related

πŸ”— Related:

FAQ

Q: When should I use const over let?

A: Prefer const for bindings that won’t be reassigned; it communicates intent and helps prevent accidental reassignments.