JavaScript Variables: var, let, and const
In JavaScript, variables are used to store data values like numbers, strings, arrays, and objects. You can declare variables using var, let, or const. Letβs understand the differences and when to use each.
πͺ 1. var β The Old Way
var was the original way to declare variables in JavaScript. It has function-level scope and can be redeclared.
var name = "Alice";
console.log(name); // Alice
var name = "Bob"; // Redeclared
console.log(name); // Bob
- Function-scoped
- Can be redeclared and reassigned
- Hoisted (but undefined at the top)
π 2. let β The Modern Standard
let is block-scoped and prevents variable redeclaration.
let age = 25;
age = 26; // β
Reassignment allowed
let age = 30; // β Error: Cannot redeclare
- Block-scoped (works inside
{}) - Can be reassigned, but not redeclared in the same scope
- Also hoisted, but not initialized
π§ 3. const β For Constants
const is also block-scoped and must be initialized when declared. The value cannot be reassigned.
const PI = 3.1416;
PI = 3.14; // β Error: Assignment to constant variable
const user = { name: "Alice" };
user.name = "Bob"; // β
Allowed (object itself not reassigned)
- Block-scoped
- Must be initialized
- Can't be reassigned, but object properties can change
βοΈ Summary: When to Use What?
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Reassignable | Yes | Yes | No |
| Redeclarable | Yes | No | No |
Best Practice: Use
let for variables that will change, and const for those that shouldnβt. Avoid var in modern JavaScript.