If you’re learning JavaScript, one of the first things you’ll encounter is how to declare variables. You might have seen var
, let
, and const
used in different places. But what’s the difference between them? When should you use each?
In this blog, we’ll explain these three keywords clearly, with examples to help you write better and bug-free code.
📝 var
– The Old Way
- Declares a function-scoped or globally scoped variable.
- Can be re-declared and updated inside the same scope.
- Has hoisting, which means the declaration is moved to the top of the scope but not the initialization.
javascriptCopyEditvar x = 10;
console.log(x); // 10
function test() {
var x = 20;
if (true) {
var x = 30; // Same variable!
console.log(x); // 30
}
console.log(x); // 30 (not 20!)
}
test();
⚠️ Problem:
var
does not have block scope — it’s only function-scoped, which can cause unexpected bugs.
📝 let
– The Modern Variable
- Introduced in ES6 (2015).
- Has block scope (inside
{}
braces). - Can be updated but cannot be re-declared in the same scope.
- Also hoisted but in a “temporal dead zone” until initialized.
javascriptCopyEditlet y = 10;
y = 20; // Allowed
// let y = 30; // Error: Identifier ‘y’ has already been declared
if (true) {
let y = 30; // Different variable, block scoped
console.log(y); // 30
}
console.log(y); // 20
📝 const
– Constants
- Also block scoped.
- Must be initialized during declaration.
- Cannot be updated or re-declared.
- However, for objects and arrays, the contents can be changed.
javascriptCopyEditconst z = 100;
// z = 200; // Error: Assignment to constant variable.
const arr = [1, 2, 3];
arr.push(4); // Allowed
console.log(arr); // [1, 2, 3, 4]
🧰 Summary Table
Feature | var | let | const |
---|---|---|---|
Scope | Function/Global | Block | Block |
Re-declaration | Allowed | Not Allowed | Not Allowed |
Re-assignment | Allowed | Allowed | Not Allowed |
Hoisting | Yes (initialized as undefined) | Yes (temporal dead zone) | Yes (temporal dead zone) |
Use Case | Legacy code | Variables that change | Constants or fixed references |
💡 Best Practices
- Avoid
var
in modern code — preferlet
andconst
. - Use
const
by default; only uselet
when you need to reassign. - Helps prevent bugs and makes your code easier to read.
Conclusion:
Understanding var
, let
, and const
is fundamental for writing clean and bug-free JavaScript. Start using let
and const
today to improve your code’s reliability and readability.
🚀 Pro Tip: Use tools like ESLint to enforce the use of
let
andconst
automatically!