When users experience slow pages, strange bugs, or things that “just don’t work right,” it's often rooted in tiny decisions — like how you declare your variables.
Yes, even var
, let
, and const
matter.
Let’s talk about what they do, and more importantly, why choosing the right one leads to better apps.
🕹️ What’s the difference?
Keyword | Scope | Reassignable? | Hoisted? | Common Bugs |
var | Function-scoped | ✅ Yes | ✅ Yes (but undefined) | Accidental overrides |
let | Block-scoped | ✅ Yes | 🚫 No (TDZ*) | Safer, but mutable |
const | Block-scoped | 🚫 No | 🚫 No | Immutable bindings |
- TDZ = Temporal Dead Zone (you can’t use the variable before it’s declared)
⚠️ Why var
is a problem
Example:
if (true) {
var message = 'Hello'
}
console.log(message) // "Hello"
It leaks out of the block, because var
ignores {}
.
This kind of behavior can cause:
- Conflicts in large codebases
- Undesired global variables
- Bugs that are hard to track in async or dynamic UIs
For the user, that might look like:
- A button stops working
- Data disappears unexpectedly
- Forms behaving inconsistently
All from an outdated keyword.
✅ Why let
and const
are safer
They respect block scope:
if (true) {
let name = 'Camila'
const age = 30
}
console.log(name) // ❌ ReferenceError
So which one should you use?
👉 Use const
by default.
It signals intent: “I won’t reassign this.”
const API_URL = '/api/posts'
👉 Use let
when the value needs to change.
let counter = 0
counter++
This makes your code more predictable, which means:
- Fewer bugs
- Easier to read
- Better behavior under pressure (e.g. user clicking fast, bad network)
🧠 Real-world example: a cart button bug
// Bad
var quantity = 1
button.addEventListener('click', () => {
console.log(quantity)
})
quantity = 5
🛑 User clicks, sees wrong quantity in console or UI.
// Good
const quantity = 1
button.addEventListener('click', () => {
console.log(quantity)
})
🟢 Now it's locked — no weirdness. What the dev sees is what the user gets.
🔄 Performance?
var
, let
, and const
perform about the same.
The difference isn’t speed — it’s clarity and correctness, which leads to better UX.
📎 Conclusions
Using let
and const
isn’t about being modern — it’s about writing code users can trust.
Every time you prevent a scope leak or an accidental reassignment, you're building an app that:
- Behaves consistently
- Handles edge cases better
- Makes users feel in control
Use const
by default. Reach for let
when needed.
And leave var
in 2009 where it belongs.