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:

01

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!
02

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!
03

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
⚡ Live Variable Behavior Simulator

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., 1user is invalid; user1 or _user is valid).
  • Case Sensitivity: totalPrice, TotalPrice, and TOTALPRICE are separate variables.
  • Reserved Keywords: Cannot use language keywords like class, return, function, typeof, or let.
  • 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:

01

1. Declaration

Reserves memory for the variable name. Defaults to undefined.

let accountBalance;
console.log(accountBalance);
// ➔ Output: undefined
02

2. Initialization

Assigns the initial value to the reserved memory slot.

accountBalance = 2500;
console.log(accountBalance);
// ➔ Output: 2500
03

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
Output
{ 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"
Output
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:

🎯 Variables Interview Deck
Question 1 of 5
⭐ Easy • Block Shadowing Scope & let
let x = 10;
{
    let x = 20;
    console.log(x);
}
console.log(x);
What will be printed to the console?
A) 10 then 20
B) 20 then 10
C) 20 then 20
D) ReferenceError
⚡ Medium • const Reference const Mutation
const numbers = [1, 2];
numbers.push(3);
console.log(numbers);
What is the result of running this code?
A) TypeError: Assignment to constant variable
B) [1, 2]
C) [1, 2, 3]
D) undefined
🔥 Hard • var Closure Trap Timers & Scope
for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 10);
}
What will be printed after 10ms?
A) 0, 1, 2
B) 3, 3, 3
C) 0, 0, 0
D) ReferenceError
⚡ Medium • TDZ Temporal Dead Zone
console.log(score);
let score = 100;
What will happen when line 1 executes?
A) ReferenceError: Cannot access 'score' before initialization
B) undefined
C) 100
D) null
⭐ Easy • const Reassignment Immutability
const MAX_SCORE = 100;
MAX_SCORE = 200;
What error is thrown on line 2?
A) SyntaxError
B) ReferenceError
C) RangeError
D) TypeError: Assignment to constant variable

7. Best Practices & Summary

  • Always default to const: Use const for all variables, functions, objects, and arrays. Only switch to let if you explicitly need to reassign the value.
  • Never use var in modern JavaScript: var leaks out of block scopes and creates accidental global variables.
  • Meaningful camelCase names: Choose descriptive names (e.g., isUserLoggedIn, cartItemCount) instead of abbreviations like x, temp, or a.
  • Remember the const reference rule: const prevents variable reassignment, not object mutation. Use Object.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.

Your output will appear here.