var vs. let/const
Understand how JavaScript's three declaration keywords differ in scope, hoisting, and reassignment: the foundation of writing predictable, bug-free code.
Why Variable Declarations Matter
Every JavaScript program stores data in variables. The keyword you choose to declare a variable controls where that variable is visible, when it exists, and whether it can be changed.
Picking the wrong keyword is one of the most common sources of subtle bugs: values that "leak" out of loops, variables that seem to exist before they're assigned, and constants that accidentally get overwritten.
What Is Scope?
Scope is the region of your code where a variable is accessible. Think of it as the variable's "visibility boundary." Outside that boundary, the variable doesn't exist.
What Is Hoisting?
Before your code runs, JavaScript "hoists" (moves) declarations to the top of their scope. But the three keywords are hoisted differently.
Scope Visualized
The Three Core Rules
Hoisting in Action
let vs. const: When to Use Which
How to Choose the Right Keyword
Example 1: var Leaks Out of Blocks
Example 2: The Classic Loop Bug
Example 3: Hoisting Surprises
JavaScript internally rewrites the var code as if it were:
const Does Not Mean Immutable
const prevents reassignment of the variable binding. It does not freeze the value itself. If the value is an object or array, its contents can still change.
Common Mistakes
Side-by-Side Comparison
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Reassignment | ✓ | ✓ | ✕ |
| Redeclaration | ✓ | ✕ | ✕ |
| Use before declare | Returns undefined | ReferenceError | ReferenceError |
| Best practice | Avoid | When reassigning | Default choice |
Question 1 of 5
What type of scope does var have in JavaScript?
Question 2 of 5
What happens when you try to access a let variable before its declaration line?
Question 3 of 5
Consider this code:
const colors = ["red", "blue"];
colors.push("green");
console.log(colors);
What is the output of the code above?
Question 4 of 5
Consider this code:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
What will be logged to the console?
Question 5 of 5
Which statement best describes the modern best practice for variable declarations in JavaScript?