Variables (var, let & const)
In JavaScript, variables are containers storing data values. Modern JavaScript provides three keywords to declare variables: var, let, and const. Understanding their scope and hoisting behaviors is crucial.
1 Scoping & Hoisting (Temporal Dead Zone)
Scoping rules control where variable declarations are visible:
- var: Function-scoped. If declared inside a block (like an `if` statement), it leaks out and is accessible outside the block. It is also **hoisted** to the top of its scope, initialized with `undefined`.
- let: Block-scoped. Accessible only inside the nearest curly braces `{}`. It is hoisted but remains uninitialized in the Temporal Dead Zone (TDZ) until execution reaches the line of declaration, throwing a ReferenceError if accessed early.
- const: Block-scoped like `let`. Must be initialized immediately on declaration, and its variable binding cannot be reassigned.
2 Scoping Codes Check
Let's run a program showing block scoping behaviors and temporal errors:
JavaScript — var, let and const Scope
▶ Run Code
if (true) {
var leakedVar = "I leak outside the block!";
let blockedLet = "I remain trapped inside.";
const blockedConst = "I am also trapped.";
}
console.log(leakedVar); // Succeeds
try {
console.log(blockedLet);
} catch (e) {
console.log("let access outside block failed: " + e.message);
}
const name = "Alice";
// name = "Bob"; // 🚨 Raises TypeError: Assignment to constant variable.
console.log("Const variable: " + name);
3 Code Challenge
Challenge: Write a block of code declaring a `const` object representing a product. Try modifying one of its properties (e.g. `product.price = 99`) and explain why changing properties is allowed on a constant declaration in JS.