A deep dive into JavaScript variable declarations, block vs function scoping, hoisting quirks, and temporal dead zone best practices.
Understanding how JavaScript stores, references, and mutates data in memory is essential for writing predictable, bug-free applications. Before ES6 (ECMAScript 2015), developers were confined to var. Today, modern development relies almost exclusively on let and const. Here is a definitive breakdown of how each keyword operates under the hood.
The most critical distinction between modern and legacy declarations lies in how lexical scopes are parsed:
var is Function-Scoped: Variables declared with var are visible throughout the entire enclosing function, completely ignoring if statements, for loops, and standalone blocks.let and const are Block-Scoped: Variables declared with let or const exist strictly within the nearest curly braces {}.function demoScope() {
if (true) {
var legacy = "I leak outside the block!";
let modern = "I remain securely trapped inside.";
}
console.log(legacy); // Works!
// console.log(modern); // ReferenceError: modern is not defined
}
While all declarations are processed during the creation phase of the execution context, they initialize very differently:
var Hoisting: Hoisted to the top of its scope and initialized with undefined. Accessing it before declaration yields undefined rather than throwing an error.let and const Hoisting: Hoisted, but placed in the Temporal Dead Zone (TDZ) from the start of the block until the evaluation of the declaration. Attempting to access them prematurely immediately throws a ReferenceError.const: Cannot be reassigned. Note that const does NOT make objects or arrays immutable—it only prevents the identifier from binding to a new memory reference.let: Designed for values that are expected to change over time, such as loop counters or accumulated state.var: Allows redeclaration within the same scope without warning, leading to silent bugs in larger codebases.const for 95% of your variable declarations.let when a variable's primitive value must be reassigned.var entirely via ESLint rules (no-var).Master the SMART goal-setting framework to turn ambitious aspirations into structured, measurable milestones for sustainable career and development growth.
Transform chaotic creative handoffs into seamless design-to-code pipelines with modern Figma component libraries and token architectures.