Variables & Declarations
Variables are named containers that store data values in memory. JavaScript has three ways to declare them: var, let, and const — each with different rules about scope and reassignment.
Without variables, you cannot store or reuse any information. They are the single most fundamental building block of any program.
Every time you need to save a value — user input, API result, counter, flag, configuration. Variables live in 'scope' — the region of code where they are accessible.
Declare with var, let, or const followed by a name, then optionally assign a value with =. Always prefer const by default, use let when the value will change, and avoid var in modern code.
📚Key Terms
Declaration— Creating a variable name in memory (let x;)
Initialization— Giving a variable its first value (let x = 5;)
Assignment— Changing a variable's value after it's declared (x = 10;)
Hoisting— JavaScript's behavior of moving var declarations to the top of their scope before code runs
Scope— The region of code where a variable is accessible and usable
Code Examples
#1var — old way (avoid in modern code)
// var is function-scoped and gets hoistedvar name = "Ali";var name = "Ahmed"; // ✅ No error — var ALLOWS re-declaration (dangerous!)// Hoisting example — var is mentally moved to the topconsole.log(age); // undefined (NOT an error — this is the bug trap!)var age = 25;console.log(age); // 25// var ignores block scope — this is why it's dangerousif (true) {var leaksOut = "I escape the block!";}console.log(leaksOut); // "I escape the block!" — oops!
#2let — block-scoped mutable variable
// let respects block scope and can be reassignedlet score = 0;score = 10; // ✅ Allowed — let CAN be reassigned// Block scope — variable dies when the block endsif (true) {let blockVar = "inside only";console.log(blockVar); // ✅ "inside only"}// console.log(blockVar); // ❌ ReferenceError — not accessible here// Perfect for loop countersfor (let i = 0; i < 3; i++) {console.log(i); // 0, 1, 2}// console.log(i); // ❌ ReferenceError — i is gone
#3const — constant reference (use by default!)
// const CANNOT be reassigned after declarationconst API_URL = "https://api.example.com";// API_URL = "other"; // ❌ TypeError: Assignment to constant variable// ⚠️ IMPORTANT: const objects/arrays CAN have their contents changed!const user = { name: "Ali", age: 25 };user.name = "Ahmed"; // ✅ ALLOWED — changing a property, not the variableuser.role = "admin"; // ✅ ALLOWED — adding a property// user = {}; // ❌ ERROR — cannot reassign the variable itselfconst colors = ["red", "green"];colors.push("blue"); // ✅ ALLOWED — modifying array contents// colors = []; // ❌ ERROR// Use const for: config values, imported modules, object/array referencesconst MAX_RETRY = 3;const baseURL = "https://api.example.com/v1";
Practice This Concept
Open the playground, paste any example, and experiment. The best way to learn is by breaking things.
Open in Playground