Variables (let, const, var)
Variables are named containers that store data. Modern JavaScript uses let for values that change and const for values that don't. Understanding the differences between let, const, and var is crucial for writing clean, bug-free code.
Variable Keywords
- const — Cannot be reassigned after declaration. Use by DEFAULT for everything
- let — CAN be reassigned. Use when value needs to change (counters, accumulators, toggles)
- var — Old way (pre-ES6). Has function scope instead of block scope. Avoid in modern code
- Rule of thumb — Always start with const. Switch to let only if you need to reassign
- Naming — camelCase: myName, totalScore, isLoggedIn. Descriptive names, not x or temp
Variables in Action
// const — value cannot change
const PI = 3.14159;
const appName = "Priygop";
const maxUsers = 1000;
// PI = 3.14; // ❌ Error! Cannot reassign const
// let — value CAN change
let score = 0;
score = 10; // ✅ OK
score += 5; // ✅ score is now 15
let userName = "Alice";
userName = "Bob"; // ✅ OK
// var — old way (avoid)
var oldStyle = "don't use this";
// var has confusing scoping rules — use let/const
// Naming conventions
let firstName = "John"; // ✅ camelCase
let total_score = 100; // ❌ snake_case (not JS convention)
const MAX_RETRIES = 3; // ✅ UPPER_CASE for true constants
let isLoggedIn = true; // ✅ boolean prefix 'is', 'has', 'can'
console.log(score); // 15
console.log(userName); // BobTry It Yourself: Variables
Tip
Tip
Name your variables descriptively — isLoggedIn, totalPrice, userName — not x, temp, or data. You read code 10x more than you write it. Clear names make your code self-documenting and save debugging time.
Use const by default, let when re-assignment is needed, never var
Common Mistake
Warning
Using var in modern code causes scope bugs. var leaks out of if/for blocks, allows redeclaration, and has confusing hoisting. Always use const by default, and let only when you need to reassign the value.
Practice Task
Note
Create variables for a user profile: (1) Use const for name, email, birthYear (they don't change). (2) Use let for age, score, isOnline (they change). (3) Calculate age from birthYear and log the full profile with template literals.
Quick Quiz
Key Takeaways
- Variables are named containers that store data.
- const — Cannot be reassigned after declaration. Use by DEFAULT for everything
- let — CAN be reassigned. Use when value needs to change (counters, accumulators, toggles)
- var — Old way (pre-ES6). Has function scope instead of block scope. Avoid in modern code