In JavaScript, variables store data values. There are three main ways to declare variables: var, let, and const. Understanding their differences is crucial for writing clean and bug-free code.

💡 Variable Declaration Overview
var– function-scoped, can be redeclared and updated.let– block-scoped, can be updated but not redeclared in the same scope.const– block-scoped, cannot be updated or redeclared; must be initialized.
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (initialized with undefined) | Yes (not initialized) | Yes (not initialized) |
| Redeclaration in same scope | Allowed | Not allowed | Not allowed |
| Reassignment | Allowed | Allowed | Not allowed |
| Must be initialized? | No | No | Yes |
⚠️ Avoid Using var in Modern Code
Because var has function scope and hoisting behavior that can cause unexpected bugs, it's best to prefer let and const in modern JavaScript.
📌 Deep Dive: Declaring Variables with let and const
let age = 30;
age = 31; // Allowed
const name = "Alice";
// name = "Bob"; // Error: Assignment to constant variable
if (true) {
let blockScoped = "inside block";
const blockConst = 100;
}
// console.log(blockScoped); // ReferenceError
name throws error, and blockScoped is not accessible outside the block.💡 Best Practices
- Use
constby default for all variables that won't change. - Use
letonly when you need to reassign the variable. - Avoid
varto prevent scope and hoisting issues.
📌 Deep Dive: var Hoisting and Scope
console.log(x); // undefined due to hoisting
var x = 5;
if (true) {
var y = 10;
}
console.log(y); // 10 - var is function-scoped, not block-scoped
10
⚠️ Redeclaring Variables
Redeclaring a variable with var in the same scope is allowed and can cause confusion. let and const prevent redeclaration in the same scope, helping avoid bugs.
💡 Summary
var: function-scoped, hoisted, can be redeclared and reassigned.let: block-scoped, hoisted but uninitialized, can be reassigned but not redeclared.const: block-scoped, hoisted but uninitialized, cannot be reassigned or redeclared; must be initialized.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which variable declaration is block-scoped and cannot be reassigned after initialization?
Question 2 of 2
What happens if you declare a variable with var inside a block (e.g., inside an if statement)?
Loading results...