2.1 Module 2 · Variables, Data Types & Functions

Variables & Declarations

Learn how to store, update, and manage data in JavaScript using var, let, and const — the building blocks of every program you'll ever write.

1

Definition

In JavaScript, a variable is a named container used to store data values that can be referenced and manipulated during program execution. Variables are declared using var, let, or const.

Every piece of data your program works with — a user's name, a score, a price — lives inside a variable. Naming it clearly makes your code readable and maintainable.

2

Simple Way

Think of a variable like a labelled box:

label The variable name — what you call it
box Memory — where JavaScript stores the value
content The value — a number, string, boolean, etc.

You can store, update, and use data inside this box at any point in your program.

3

Code Examples

Example 1 — var, let, and const
var name = "Aman";
let age = 22;
const country = "India";

console.log(name);
console.log(age);
console.log(country);
Output
Click ▶ Run to execute
Explanation
  • var → old way of declaring variables (function-scoped, avoid in modern code)
  • let → modern declaration whose value can be changed later
  • const → fixed value that cannot be reassigned after declaration
Example 2 — Declaration, Initialization & Reassignment
let score;       // Declaration — variable created, value is undefined
score = 10;      // Initialization — first value assigned
score = 20;      // Reassignment — value updated

console.log(score);
Output
Click ▶ Run to execute
Explanation
  • Declaration → creates the named container in memory
  • Initialization → stores a value in it for the first time
  • Reassignment → replaces the value with a new one (only works with let / var)
Example 3 — const Cannot Be Reassigned
const pi = 3.14;
console.log(pi);

// Trying to reassign const — this throws an error:
try {
  pi = 3.14159;
} catch (e) {
  console.log("Error:", e.message);
}
Output
Click ▶ Run to see the error
Explanation
  • const locks the binding — once assigned, the variable cannot point to a new value
  • Attempting to reassign throws a TypeError at runtime
4

Real-Life Example

Imagine managing your wallet and identity documents:

let
Your wallet balance — it changes every time you spend or earn
const
Your Aadhaar number — fixed for life, never reassigned
var
An old-style notebook — works but causes confusion in large codebases
name
The label on the box — clear names make code readable instantly
5

HTML + JavaScript Example

Variables power everything on a real page. Click ▶ Preview, then press the button inside to see variables displayed live in the browser.

Live in Browser — Variables Demo
<!DOCTYPE html>
<html>
<head><title>Variables Demo</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>JavaScript Variables</h2>
  <button onclick="showVars()"
    style="padding:8px 20px;background:#f7df1e;border:none;
           border-radius:6px;cursor:pointer;font-weight:700;font-size:1rem">
    Click Me
  </button>
  <div id="output" style="margin-top:16px;line-height:2"></div>

  <script>
    function showVars() {
      const userName = "Aman";
      let age = 22;
      let wallet = 1000;

      wallet -= 300; // spent ₹300

      document.getElementById("output").innerHTML =
        "<b>Name:</b> "   + userName + "<br>" +
        "<b>Age:</b> "    + age      + "<br>" +
        "<b>Wallet:</b> ₹" + wallet;
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Your identity variables
Starter code
// Replace values with your own
let name = "Your Name";
let city = "Your City";
  • Declare name and city using let
  • Print both with console.log()
Medium Task 2 — Marks tracker
Starter code
let marks = 50;
  • Increase marks by 20 using +=
  • Print the final marks with a label — e.g. "Final marks: 70"
  • Try changing let to const — what happens?
7

MCQs

Q1
Which keyword is used to declare a constant variable?
  • A var
  • B let
  • C const
  • D static
💡 C is correct. const declares a variable whose binding cannot be reassigned. Use it whenever you know the value should never change.
Q2
Which variable declaration allows reassignment?
  • A const
  • B let
  • C Both
  • D Neither
💡 B is correct. let allows the value to be updated at any time. const locks the binding after the first assignment.
Q3
What happens when you run this code?
const x = 10;
x = 20;
Output
Run it to verify
  • A Works fine — x becomes 20
  • B Error — cannot reassign const
  • C undefined
  • D null
💡 B is correct. Reassigning a const throws a TypeError at runtime. The first assignment is the only one allowed.
8

Pro Tips & Extra Knowledge

  • 01

    Prefer const by default — only switch to let when you know the value will change. This prevents accidental reassignment bugs.

    const first, let when needed
    const taxRate = 0.18;   // never changes
    let cartTotal = 500;    // will be updated
    
    cartTotal += 200;
    console.log(cartTotal);
    console.log(taxRate);
    Output
    Click ▶ Run to execute
  • 02

    Use meaningful variable names — code is read far more often than it is written:

    Good vs bad naming
    let userAge = 25;   // ✓ clear intent
    let x = 25;         // ✗ what is x?
    
    const maxRetries = 3;   // ✓ self-documenting
    const n = 3;            // ✗ meaningless
    
    console.log(userAge, maxRetries);
    Output
    Click ▶ Run to execute
  • 03

    Avoid var in modern JavaScript. It is function-scoped (not block-scoped), which causes subtle bugs in loops and conditionals that let and const prevent entirely.

  • 04

    Use camelCase for variable names — it is the JavaScript convention:

    camelCase convention
    let firstName  = "Priya";   // ✓ camelCase
    let first_name = "Priya";   // ✗ snake_case (Python style)
    let FirstName  = "Priya";   // ✗ PascalCase (reserved for classes)
    
    console.log(firstName);
    Output
    Click ▶ Run to execute
Mini Challenge

Predict both outputs before running — think about how values are copied between variables.

What does this print?
let a = 10;
let b = a;

b = 20;

console.log(a);
console.log(b);
Output
Think first, then run!
Step-by-Step Explanation
// Step 1: a = 10
//         a → [10]

// Step 2: b = a
//         b gets a COPY of the value — not a reference
//         b → [10]   (a is still [10])

// Step 3: b = 20
//         only b changes — a is unaffected
//         b → [20]   a → [10]

// Output:
//   10   ← a is unchanged
//   20   ← b was updated independently

// Key takeaway: primitive values (numbers, strings, booleans)
// are copied by VALUE — changing b never affects a.