Introduction
JavaScript gives us three ways to declare variables: var, let, and const.
At first, they may look similar but they behave very differently when it comes to scope, hoisting, and reassignment. Choosing the wrong one can lead to bugs that are hard to track.
Let’s break them down step by step.
What Is var in JavaScript?
var is the old way of declaring variables in JavaScript.
Example
var name = "Ali";
Key Characteristics
- Function-scoped
- Hoisted with
undefined - Can be redeclared
- Can be reassigned
Scope Differences
var Scope
var is function-scoped, not block-scoped.
if (true) {
var age = 25;
}
console.log(age); // 25
⚠️ This can cause unexpected behavior.
let and const Scope
let and const are block-scoped.
if (true) {
let city = "Mogadishu";
}
console.log(city); // Error
✔ Much safer and predictable.
Hoisting Behavior Explained
Hoistingwith var
console.log(x);
var x = 10;
Output: undefined
var is hoisted and initialized with undefined.
Hoistingwith let and const
console.log(y);
let y = 5;
❌ Error:
ReferenceError: Cannot access 'y' before initialization
This happens because of the Temporal Dead Zone (TDZ).
Redeclaration Rules
var Allows Redeclaration
var score = 10;
var score = 20;
✔ No error (but risky).
let and const Do NOT
let score = 10;
let score = 20; // Error
✔ Prevents accidental overwrites.
Reassignment Differences
var and let
let count = 1;
count = 2; // Allowed
const
const PI = 3.14;
PI = 3.15; // Error
⚠️ const means the variable reference cannot change.
Important Note About const Objects
You can modify object properties declared with const.
const user = { name: "Ali" };
user.name = "Ahmed"; // Allowed
✔ The reference stays the same.
Comparison Table
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Redeclaration | Yes | No | No |
| Reassignment | Yes | Yes | No |
| Recommended | ❌ | ✅ | ✅ |
When to Use What
- ✅ Use
constby default - ✅ Use
letwhen value needs to change - ❌ Avoid
varin modern JavaScript
Common Beginner Mistakes
- Using
varout of habit - Thinking
constmeans “immutable” - Accessing
letvariables too early - Mixing scopes accidentally
Best Practices
- Always start with
const - Switch to
letonly when needed - Never use
varin modern code - Keep variable scopes small and clear
Conclusion
Understanding the differences between var, let, and const is essential for writing clean, predictable JavaScript. Modern JavaScript favors let and const because they reduce bugs and improve readability.
At Developer Hint we focus on explaining JavaScript concepts clearly, helping you write better code with confidence.
Discover more from Developer Hint
Subscribe to get the latest posts sent to your email.








Leave a Reply