JavaScript Variables: var, let & const
Variables are the building blocks of any programming language. In JavaScript, you use them to store data, reuse values, and write clean, maintainable code. Let's break down the three ways to declare variables in JavaScript: var
, let
, and const
.
1. What Are Variables?
A variable is like a container that holds a value — it could be a number, text, object, or more. Think of it like naming a box so you know what’s inside.
let name = "Alice";
const age = 25;
var city = "New York";
2. The Old Way: var
var
was the only way to declare variables before ES6 (2015). It's function-scoped and allows redeclaration — but that can lead to bugs.
var score = 10;
var score = 20; // ✅ allowed
function testVar() {
var x = 1;
if (true) {
var x = 2;
console.log(x); // 2
}
console.log(x); // 2
}
3. The Better Way: let
Use let
when the value of your variable might change. It’s block-scoped, so it behaves better inside loops and conditionals.
let count = 1;
count = 2; // ✅ allowed
if (true) {
let count = 3;
console.log(count); // 3
}
console.log(count); // 2
4. The Constant Way: const
Use const
when your variable should never change. It must be assigned a value when declared and can’t be reassigned.
const pi = 3.14;
// pi = 3.14159; ❌ Error
const user = { name: "John" };
user.name = "Jane"; // ✅ allowed (object values can change)
5. Comparison Table
Feature | var | let | const |
---|---|---|---|
Scope | Function | Block | Block |
Reassignable | ✅ | ✅ | ❌ |
Redeclarable | ✅ | ❌ | ❌ |
Hoisted | ✅ (undefined) | ✅ (TDZ) | ✅ (TDZ) |
6. Final Tips
- Use
const
by default unless you need to reassign. - Use
let
when the value changes. - Avoid
var
unless working on legacy projects.