JavaScript Variables
Master variable declaration, memory allocation, scope behavior, naming rules, and immutable bindings in JavaScript.
1. What is a Variable?
A variable is simply a labeled container for storing data in your program. You give the container a name (like score), put some data inside it (like 100), and use that name whenever you want to read or update that data.
💡 Think of labeled storage boxes
Think of variables as labeled boxes in a storage room:
• const is a locked steel safe: once closed, you cannot swap the safe out for another box.
• let is a reusable cardboard box: you can swap or update the contents anytime.
• var is an old leaky wooden crate from 1995: its contents leak outside the room (function-scoped, ignoring blocks)!
2. The Three Keywords: const, let, and var
JavaScript has 3 keywords to declare variables. Here is the easiest way to understand the difference:
const (Locked 🔒)
Use by default (95% of the time)
- Value cannot be changed
- Safe: stays inside its
{}block - Cannot declare same name twice
const PI = 3.14;
// PI = 3.15; ❌ Error!
let (Changeable 📦)
Use only when value must change
- Value can be updated anytime
- Safe: stays inside its
{}block - Cannot declare same name twice
let score = 10;
score = 25; // ✅ Updated!
var (Old / Avoid ⚠️)
Never use in modern JavaScript
- Value can be updated
- Leaks outside
{}blocks - Can accidentally overwrite names
var old = "1995";
var old = "buggy"; // ⚠️ Leaks
3. Variable Naming Rules & Conventions
JavaScript identifiers must strictly adhere to lexical grammar rules:
- Valid Characters: Letters (
a-z, A-Z), digits (0-9), underscores (_), and dollar signs ($). - First Character Rule: Identifiers cannot begin with a digit (e.g.,
1useris invalid;user1or_useris valid). - Case Sensitivity:
totalPrice,TotalPrice, andTOTALPRICEare separate variables. - Reserved Keywords: Cannot use language keywords like
class,return,function,typeof, orlet. - Industry Conventions: Use camelCase for variables and functions (e.g.,
userAge), PascalCase for classes and React components (e.g.,UserProfile), and UPPER_SNAKE_CASE for fixed configuration constants (e.g.,MAX_RETRY_COUNT).
| Identifier Name | Status | Rule / Explanation |
|---|---|---|
let userName; |
✅ Valid | Standard camelCase letters |
let _token, $price; |
✅ Valid | Identifiers can start with _ or $ |
let 2users; |
❌ Invalid | Identifiers cannot start with numbers (SyntaxError) |
let user-name; |
❌ Invalid | Hyphens are interpreted as subtraction operators |
let function; |
❌ Invalid | Reserved JavaScript language keyword |
4. Declaration vs Initialization vs Reassignment
Understanding the lifecycle of a variable in memory:
1. Declaration
Reserves memory for the variable name. Defaults to undefined.
let accountBalance;
console.log(accountBalance);
// ➔ Output: undefined
2. Initialization
Assigns the initial value to the reserved memory slot.
accountBalance = 2500;
console.log(accountBalance);
// ➔ Output: 2500
3. Reassignment
Overwrites the existing memory slot with a new value.
accountBalance = 5000;
console.log(accountBalance);
// ➔ Output: 5000
💡 Best Practice: Combined Declaration & const Rule
• In modern JavaScript, always combine declaration and initialization together: let level = 5;
• Important: const variables must be initialized immediately upon declaration (e.g., const API_KEY = "live_secret";). Leaving const API_KEY; throws a SyntaxError!
Reassignment vs Redeclaration Rules
// 1. var: Allows BOTH redeclaration and reassignment
var name = "Alex";
var name = "Sam"; // ✅ Allowed (Redeclared)
name = "Jordan"; // ✅ Allowed (Reassigned)
// 2. let: Can reassign, CANNOT redeclare
let score = 10;
// let score = 20; // ❌ Error: Cannot redeclare
score = 20; // ✅ Allowed (Reassigned)
// 3. const: CANNOT redeclare, CANNOT reassign (Locked)
const max = 100;
// const max = 200; // ❌ Error: Cannot redeclare
// max = 150; // ❌ Error: Cannot reassign
5. const with Objects and Arrays (The Reference Trap)
A classic technical interview question: "If a variable is declared with const, why can we still add properties to it?"
const creates an immutable variable binding (it locks the memory pointer in stack memory), but it does not make the object or array value stored in heap memory immutable. You can mutate its keys and indices freely.
const student = { name: "Anshuman", semester: 6 };
// ✅ Allowed: Mutating internal properties
student.semester = 7;
student.gpa = 3.9;
console.log(student);
// ❌ Forbidden: Reassigning the variable reference to a different object
// student = { name: "Priya" }; // ❌ TypeError: Assignment to constant variable
const languages = ["JavaScript", "Python"];
// ✅ Allowed: Adding or modifying elements
languages.push("TypeScript");
languages[0] = "Modern JavaScript";
console.log(languages);
// ❌ Forbidden:
// languages = ["Rust", "Go"]; // ❌ TypeError: Assignment to constant variable
{ name: 'Anshuman', semester: 7, gpa: 3.9 }
[ 'Modern JavaScript', 'Python', 'TypeScript' ]
💡 Mental Model: House Address vs Furniture Inside
Think of const as your permanent residential address. You cannot change your home address (reassign the reference), but you can paint your living room walls, buy a new sofa, and replace the carpet inside your house anytime (mutate properties)! To make the contents inside completely immutable as well, use Object.freeze().
6. Variable Shadowing
When an identifier declared in an inner scope (such as a block or a function) shares the exact same name as an identifier in an outer scope, the inner variable shadows (masks) the outer variable within that block without altering the outer value.
let score = 50; // Outer variable
function playLevel() {
let score = 95; // Shadows outer 'score' inside this function scope
console.log("Inner function score:", score); // 95
}
playLevel();
console.log("Outer scope score:", score); // 50 (preserved!)
// Block-level shadowing with let / const:
let theme = "light";
if (true) {
let theme = "dark"; // Block-scoped shadow
console.log("Inside conditional block:", theme); // "dark"
}
console.log("Outside block:", theme); // "light"
Inner function score: 95 Outer scope score: 50 Inside conditional block: dark Outside block: light
7. Variables Interview Deck
Test your knowledge with 5 classic JavaScript variable interview questions asked by top companies:
7. Best Practices & Summary
- Always default to
const: Useconstfor all variables, functions, objects, and arrays. Only switch toletif you explicitly need to reassign the value. - Never use
varin modern JavaScript:varleaks out of block scopes and creates accidental global variables. - Meaningful camelCase names: Choose descriptive names (e.g.,
isUserLoggedIn,cartItemCount) instead of abbreviations likex,temp, ora. - Remember the
constreference rule:constprevents variable reassignment, not object mutation. UseObject.freeze()for deep immutability. - Avoid shadowing in production: While legal, variable shadowing can cause accidental name collisions and tricky debugging scenarios.
Interactive Practice Challenge
Create a const object called student with properties name and an array of skills. Mutate the object by adding a new skill and a new property grade without reassigning the reference. Then demonstrate variable shadowing with a variable named city inside an if block.