DEV Community

Cover image for VAR, LET, & CONST in JavaScript

VAR, LET, & CONST in JavaScript

🤹‍♂️ var, let, and const in JavaScript

Three variables walk into a scope… and only two behave properly

If you’ve worked with JavaScript, you’ve definitely met these three:

var
let
const
Enter fullscreen mode Exit fullscreen mode

They look similar.
They behave very differently.
And one of them (var) is responsible for a lot of emotional damage in production systems 😄

Let’s understand what really happens behind the scenes, without jargon overload and without falling asleep.


🧠 How JavaScript Runs Your Code (Very Important)

JavaScript doesn’t execute your code line by line immediately.
It first prepares everything, then runs it.

JavaScript runs in two phases:

1️⃣ Memory Creation Phase

The JS engine:

  • Scans the entire code
  • Allocates memory for variables & functions
  • Does not assign actual values yet

2️⃣ Execution Phase

  • Executes code line by line
  • Assigns values
  • Runs functions

This all happens inside something called an Execution Context.


🧪 var — The OG Troublemaker

Let’s start with an example everyone has seen:

console.log(a);
var a = 10;
Enter fullscreen mode Exit fullscreen mode

Expected by beginners:

❌ Error

Given by JavaScript:

undefined

Why? Because JavaScript is… forgiving.

Behind the scenes 👇

Memory Phase

a  undefined
Enter fullscreen mode Exit fullscreen mode

Execution Phase

console.log(a); // undefined
a = 10;
Enter fullscreen mode Exit fullscreen mode

Key takeaways about var

  • ✅ Hoisted
  • ✅ Initialized with undefined
  • ❌ Not block-scoped
  • ❌ Can be redeclared
  • ❌ Easy to mess up

🚨 var Does Not Respect Block Scope

if (true) {
  var secret = "I should not escape";
}

console.log(secret); // 😱 It escaped
Enter fullscreen mode Exit fullscreen mode

Why?

  • var is function-scoped
  • {} blocks mean nothing to it

This behavior caused real bugs in real applications, which is why let and const were introduced.


🧠 Enter let — The Responsible One

console.log(b);
let b = 20;
Enter fullscreen mode Exit fullscreen mode

❌ Error:

ReferenceError: Cannot access 'b' before initialization
Enter fullscreen mode Exit fullscreen mode

But wait… isn’t let hoisted?

👉 Yes, it is hoisted. Plot twist.

So why the error?


⏳ Temporal Dead Zone (TDZ) — Explained Simply

TDZ is the time between:

  • Memory allocation
  • Variable initialization

Memory Phase

b  <uninitialized>
Enter fullscreen mode Exit fullscreen mode

Execution Phase

console.log(b); // ❌ TDZ error
b = 20;         // TDZ ends here
Enter fullscreen mode Exit fullscreen mode

The JS engine basically says:

“I know you exist… but don’t touch me yet.”


🔐 Block Scope (Finally!)

if (true) {
  let score = 100;
}

console.log(score); // ❌ ReferenceError
Enter fullscreen mode Exit fullscreen mode

Unlike var, let respects block boundaries.
Much safer. Much cleaner.


🔒 const — The Strict One

const pi = 3.14;
pi = 3.14159; // ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

Rules of const:

  • Must be initialized immediately
  • Cannot be reassigned
  • Block-scoped
  • Hoisted (with TDZ)
const x; // ❌ SyntaxError
Enter fullscreen mode Exit fullscreen mode

JavaScript wants commitment here.


🤯 The Famous const + Object Confusion

const user = { name: "Hardeep" };

user.name = "Singh"; // ✅ Allowed
user = {};           // ❌ Not allowed
Enter fullscreen mode Exit fullscreen mode

Why?

Because const means:

“The reference cannot change, not the contents.”

Think:

  • Address is fixed
  • Furniture inside can move

📊 Quick Comparison Table

Feature var let const
Scope Function Block Block
Hoisted Yes Yes Yes
Initialized on hoisting undefined ❌ TDZ ❌ TDZ
Redeclare
Reassign
Recommended today ❌ No ✅ Yes ✅ Yes

🧠 Behind the Scenes (Slightly Nerdy)

Internally, JavaScript maintains:

  • Variable Environmentvar
  • Lexical Environmentlet & const

That’s why:

  • var leaks scope
  • let and const don’t

🚀 Best Practices (Learned the Hard Way)

  • ✅ Use const by default
  • ✅ Use let only when reassignment is required
  • ❌ Avoid var unless you’re working on legacy code

If JavaScript were designed today, var probably wouldn’t exist.


🎯 Final Thoughts

  • var → risky and outdated
  • let → safe and flexible
  • const → safest and preferred

JavaScript didn’t get weird.
We just finally understood how it works 😄

So, whether you're seeking JS advice, a good laugh, or simply a friendly chat about code and coffee preferences, I'm just a click away on these cloud-astic platforms.

LinkedIn: 🚀💼 hardeepjethwani@LinkedIn

TopMate: ☕🤝 hardeepjethwani@topmate

Instagram: 📸🌩️ hardeepjethwani@Instagram

X: 🐦☁️ hardeepjethwani@X

Top comments (0)