JavaScript Variables (let, const, var)
Complete guide to variable declarations, block scoping, TDZ, and immutability in modern JavaScript.
Overview
In modern JavaScript (ES6+), variable declarations should prioritize const and let over legacy var. Understanding how hoisting, block scope, and the Temporal Dead Zone (TDZ) operate is foundational to writing bug-free JavaScript.
Comparison Summary
| Keyword | Scope | Hoisted | Temporal Dead Zone | Re-assignable | Re-declarable |
|---|---|---|---|---|---|
const | Block {} | Yes (uninitialized) | Yes | ❌ No | ❌ No |
let | Block {} | Yes (uninitialized) | Yes | ✅ Yes | ❌ No |
var | Function () | Yes (initialized undefined) | ❌ No | ✅ Yes | ✅ Yes |
1. const (Constant Declarations)
Always use const by default unless you know the variable value needs to be reassigned.
const API_URL = "https://api.example.com";
const user = { name: "Alex", role: "developer" };
// Valid: mutating properties of a const object
user.role = "lead";
// TypeError: Assignment to constant variable.
// API_URL = "https://other.com";2. let (Block-Scoped Mutable Variables)
Use let when a value will be reassigned (e.g. counters in loops, state accumulators):
let count = 0;
for (let i = 0; i < 5; i++) {
count += i;
}
console.log(count); // 10
// console.log(i); // ReferenceError: i is not defined3. The Temporal Dead Zone (TDZ)
Variables declared with let and const exist in the Temporal Dead Zone from the beginning of their enclosing block until execution reaches the declaration line:
{
// TDZ begins
// console.log(temp); // ReferenceError: Cannot access 'temp' before initialization
let temp = 42; // TDZ ends
console.log(temp); // 42
}Best Practices
- Default to
const: 90%+ of your variables should be declared withconst. - Use
letonly for stateful changes: Loop iterators, conditional reassignment. - Avoid
var:varlacks block scoping and silently pollutes global or function scopes.
Introduction to JavaScript
Understanding JavaScript: ECMAScript standards, browser V8 vs Node.js runtimes, dynamic typing, and the role of JavaScript in web development.
JavaScript Data Types & Type Coercion
Mastering JavaScript data types: 7 primitives (string, number, bigint, boolean, undefined, null, symbol), Objects, typeof operator, and type coercion.