learn2kode.in

JavaScript Variables (var, let, const)

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.

1. var – The Old Way

var was the original way to declare variables in JavaScript.
However, it has some issues, so modern JavaScript recommends using let or const instead

Features of var
Example
var name = "John";
console.log(name); // John

var name = "David"; // Redeclaration allowed
console.log(name); // David
Why you should avoid var

2. let – The Modern, Safe Variable

let is the recommended way to declare variables that can change later.

Features of let
Example
let age = 25;
age = 26; // allowed
console.log(age); // 26

let age = 30; 
// ❌ Error: cannot redeclare 'age'
Block Scope Example
if (true) {
    let x = 10;
}
console.log(x); // ❌ Error: x is not defined

3. const – For Values That Should Not Change

const is used for variables that should stay constant (unchanged).

Features of const
Example
const country = "India";
console.log(country); // India

country = "USA"; 
// ❌ Error: Assignment to constant variable

Important Note About const and Objects/Arrays

The variable itself cannot change, but the content inside an object or array can change.

Example with Array
const numbers = [1, 2, 3];
numbers.push(4); // allowed
console.log(numbers); // [1, 2, 3, 4]
Example with Object
const user = { name: "learn2kode" };
user.name = "Suraj"; // allowed
console.log(user.name); // Suraj

Quick Comparison Table

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)

Which One Should You Use?

Use this rule:

Simple Example to Remember All Three
var city = "Chennai"; // old way
let score = 10;       // value will change
const pi = 3.14;      // value stays constant

score = 20;          // ✔ allowed
pi = 22;             // ❌ error