JavaScript Variables Explained: The Difference Between let, const and var

JavaScript Variables Explained: The Difference Between let, const and var

In JavaScript, variables are used to store data.

But there are three different ways to declare variables:

  • var
  • let
  • const

They look similar… but they behave very differently.

Let’s break it down clearly.


🔹 What is a Variable?

A variable is a container that stores a value.

Example:

let name = "Codex Cider";

Here:

  • name is the variable
  • "Codex Cider" is the value

🔹 1. var (The Old Way)

var was the original way to declare variables in JavaScript.

Example:

var age = 20;

Problems with var

  • Function scoped (not block scoped)
  • Can be redeclared
  • Can be updated
  • Hoisted in a confusing way

Example

if (true) {
  var x = 10;
}

console.log(x); // 10
Output: 10

Even though x is inside the block, it is still accessible outside.

This can cause bugs.


🔹 2️. let (Modern and Safer)

let was introduced in ES6.

let count = 5;

Features of let

  • Block scoped ✅
  • Can be updated ✅
  • Cannot be redeclared ❌
  • Safer than var ✅

Example

if (true) {
  let y = 20;
}

console.log(y); // Error
Error: y is not defined

🔹 3️. const (Constant Variable)

const is used for values that should not change.

const pi = 3.14;

Features of const

  • Block scoped ✅
  • Cannot be updated ❌
  • Cannot be redeclared ❌
  • Must be initialized immediately ✅

Example

const score = 100;
score = 200; // Error
Error: Assignment to constant variable.

🔹 Important Note About const

With objects:

const user = { name: "John" };
user.name = "Mike"; // Allowed

You cannot reassign the variable —
but you can modify the object inside it.


🔹 Hoisting Difference

var

console.log(a);
var a = 5;

Output:

undefined

let and const

console.log(b);
let b = 10;

Output:

ReferenceError

This happens because of something called the Temporal Dead Zone (TDZ).


🔹 Quick Comparison Table

Featurevarletconst
ScopeFunctionBlockBlock
Redeclare
Update
HoistedYes (undefined)Yes (TDZ)Yes (TDZ)
Modern Usage❌ Avoid✅ Yes✅ Yes

🔹 When Should You Use Each?

✔ Use const by default
✔ Use let when value changes
❌ Avoid var in modern JavaScript


🔹 Best Practice Rule

Start with const.
Switch to let only if needed.

Simple and clean.


🔹 Conclusion

Understanding var, let, and const is essential for writing clean JavaScript.

  • var → outdated
  • let → flexible
  • const → safest default

Modern JavaScript mostly uses:

const + let