Variables
EasyVariables are containers that store data values. JavaScript has three ways to declare variables: var (old), let (modern), and const (constant). Understanding their differences is fundamental to writing good JavaScript.
Interactive Visualization
CodeCreation Phase
1console.log(x);2var x = 5;3console.log(x);
VariablesCreating...
varx=undefinedhoisted
Console Output
No output yet
Step 1/5Before execution starts, JavaScript scans the code and hoists var declarations to the top.
Key Insight:var declarations are hoisted to the top of their scope and initialized with undefined. The assignment stays where you wrote it.
Keywords:
var (function scope)
let (block scope)
const (constant)
States:
hoisted
TDZ
initialized
Key Points
- var: function-scoped, can be redeclared, hoisted with undefined
- let: block-scoped, cannot be redeclared, hoisted but in TDZ
- const: block-scoped, cannot be reassigned, must be initialized
- Use const by default, let when you need to reassign
- Avoid var in modern JavaScript
Code Examples
Declaring Variables
var oldWay = "I'm old school"; let modern = "I can change"; const fixed = "I stay the same"; modern = "See, I changed!"; // OK // fixed = "Try to change me"; // Error!
var is the old way, let allows reassignment, const is constant
const with Objects
const person = { name: "Alice" }; // This WORKS! We're changing the object, not the binding person.name = "Bob"; person.age = 25; // This FAILS! Can't reassign the variable // person = { name: "Charlie" }; // Error!
const prevents reassignment, not mutation of objects
Block Scope
if (true) { var x = 1; // Function scoped let y = 2; // Block scoped const z = 3; // Block scoped } console.log(x); // 1 (var leaks out!) // console.log(y); // Error: y is not defined // console.log(z); // Error: z is not defined
let and const respect { } blocks, var does not
Common Mistakes
- Using var in modern code (prefer let/const)
- Thinking const makes objects immutable (it doesn't)
- Not initializing const (const x; is invalid)
Interview Tips
- Know the difference between var, let, and const
- Explain scope differences (function vs block)
- Default to const, use let only when needed