Variables are used to store data in JavaScript. Think of a variable as a container where you put a value and use it later in your code. JavaScript allows you to create variables using three keywords:
Each one behaves differently, so it’s important to understand how they work.
var was the original way to declare variables in JavaScript.
However, it has some issues, so modern JavaScript recommends using let or const instead
var name = "John";
console.log(name); // John
var name = "David"; // Redeclaration allowed
console.log(name); // David
let is the recommended way to declare variables that can change later.
let age = 25;
age = 26; // allowed
console.log(age); // 26
let age = 30;
// ❌ Error: cannot redeclare 'age'
if (true) {
let x = 10;
}
console.log(x); // ❌ Error: x is not defined
const is used for variables that should stay constant (unchanged).
const country = "India";
console.log(country); // India
country = "USA";
// ❌ Error: Assignment to constant variable
The variable itself cannot change, but the content inside an object or array can change.
const numbers = [1, 2, 3];
numbers.push(4); // allowed
console.log(numbers); // [1, 2, 3, 4]
const user = { name: "learn2kode" };
user.name = "Suraj"; // allowed
console.log(user.name); // Suraj
| Feature | var | let | const |
|---|---|---|---|
| Redeclaration | ✔ Allowed | ✖ Not allowed | ✖ Not allowed |
| Updating Value | ✔ Allowed | ✔ Allowed | ✖ Not allowed |
| Scope Type | Function scope | Block scope | Block scope |
| Hoisting | Yes (initialized as undefined) | Yes (not initialized) | Yes (not initialized) |
| Recommended? | ❌ No | ✔ Yes | ✔ Yes (for fixed values) |
Use this rule:
var city = "Chennai"; // old way
let score = 10; // value will change
const pi = 3.14; // value stays constant
score = 20; // ✔ allowed
pi = 22; // ❌ error