Home/Concepts/Variables
📦
Beginner⏱ 8 min#01 / 08

Variables

var, let & const

Variables are named containers that store data values. JavaScript offers three declaration keywords - var, let, and const - each with different scoping and mutation rules.

Your Progress0/8 complete
0 visited0%
💡 Real-World Analogy

Think of variables like labeled boxes. var is an old cardboard box that can wander anywhere in the house (function-scoped and hoisted). let is a plastic box that stays in the room you put it in (block-scoped). const is a sealed box - once you fill it, you cannot swap it out.

🔑 Key Concepts

var

Function-scoped, hoisted to top of function, can be redeclared & reassigned. Avoid in modern code.

let

Block-scoped, not accessible before declaration (TDZ), cannot be redeclared but CAN be reassigned.

const

Block-scoped, must be assigned on declaration, cannot be reassigned. Use for values that never change.

💻 Code Examples

1Basic Declaration
variables.js
1// var - function-scoped, old style
2var name = "Thunder";
3var name = "Course"; // allowed: redeclare
4name = "JavaScript"; // allowed: reassign
5 
6// let - block-scoped, modern
7let age = 18;
8// let age = 20; // Error: cannot redeclare
9age = 21; // allowed: reassign
10 
11// const - block-scoped, fixed reference
12const PI = 3.14159;
13// PI = 3; // Error: cannot reassign
2Scope & Hoisting
variables.js
1// var leaks out of blocks
2if (true) {
3 var leaked = "I escaped the block";
4 let safe = "I stay inside";
5}
6console.log(leaked); // "I escaped the block"
7// console.log(safe); // ReferenceError
8 
9// Hoisting - var is undefined, let errors
10console.log(x); // undefined (hoisted)
11var x = 5;
12// console.log(y); // ReferenceError (TDZ)
13let y = 10;
3const with Objects & Arrays
variables.js
1// const prevents reassignment, not mutation
2const person = { name: "Alex", age: 20 };
3person.name = "Sam"; // allowed: mutate property
4person.city = "NYC"; // allowed: add property
5// person = {}; // Error: cannot reassign ref
6 
7const colors = ["red", "blue"];
8colors.push("green"); // allowed: mutate array
9console.log(colors); // ["red", "blue", "green"]

⚠️ Common Mistakes

❌ Mistake

Using var in modern code

✅ Fix

Use const by default, let when you need to reassign. Avoid var entirely.

❌ Mistake

Thinking const means the value is frozen

✅ Fix

const prevents REASSIGNING the variable. Object & array contents can still change.

❌ Mistake

Declaring variables without any keyword

✅ Fix

Undeclared variables become implicit globals - a serious bug source!

📋 Quick Reference

var → function-scoped, hoistedlet → block-scoped, not hoistedconst → block-scoped, must initializeBest rule: const > let > var

Live Code Playground

Edit the code and press ▶ Run to see output instantly.

variables_playground.js
⟳ Loading editor...
💾 Auto-saved
// Press ▶ Run Code to execute and view output console logs...
Challenge Mode
Next →
Strings
🔤