Variables
var, let & const
Variables are named containers that store data values. JavaScript offers three declaration keywords - var, let, and const - each with different scoping and mutation rules.
Think of variables like labeled boxes. var is an old cardboard box that can wander anywhere in the house (function-scoped and hoisted). let is a plastic box that stays in the room you put it in (block-scoped). const is a sealed box - once you fill it, you cannot swap it out.
🔑 Key Concepts
Function-scoped, hoisted to top of function, can be redeclared & reassigned. Avoid in modern code.
Block-scoped, not accessible before declaration (TDZ), cannot be redeclared but CAN be reassigned.
Block-scoped, must be assigned on declaration, cannot be reassigned. Use for values that never change.
💻 Code Examples
⚠️ Common Mistakes
Using var in modern code
Use const by default, let when you need to reassign. Avoid var entirely.
Thinking const means the value is frozen
const prevents REASSIGNING the variable. Object & array contents can still change.
Declaring variables without any keyword
Undeclared variables become implicit globals - a serious bug source!
📋 Quick Reference
Live Code Playground
Edit the code and press ▶ Run to see output instantly.