Courses/JavaScript Programming/Variables - let, const, var

Variables - let, const, var

Store and manage data

Beginner⏱️ 10 minutes

Lesson Content

JavaScript Variables

What Are Variables?

Variables are containers that store data values. They're the foundation of programming—without them, you couldn't remember or manipulate data!

Why Variables Matter

  • Store Data: Remember user inputs, API responses, calculations
  • Reusability: Use the same value multiple times
  • Dynamic Programs: Values change as your program runs
  • Readable Code: userName is clearer than hardcoded strings

How Variables Work

  1. Declare: Create the variable (let age)
  2. Initialize: Give it a value (age = 25)
  3. Use: Reference it by name (console.log(age))

Three Ways to Declare

let - Reassignable Variables

let score = 0;      // Initialize
score = 10;         // ✅ Can change
score = 20;         // ✅ Can change again

const - Constants (Cannot Change)

const PI = 3.14159;
PI = 3.14;          // ❌ Error! Cannot reassign

var - Old Way (Avoid!)

var oldWay = "outdated";  // ❌ Has weird scoping issues

Data Types You Can Store

let text = "Hello";        // String (text)
let number = 42;           // Number (integer or decimal)
let price = 19.99;         // Number (decimals work too)
let isActive = true;       // Boolean (true/false)
let emptyValue = null;     // Null (intentionally empty)
let notSet;                // Undefined (not assigned yet)

Naming Rules & Best Practices

// ✅ Good Names (camelCase)
let userName = "Alice";
let totalPrice = 99.99;
let isLoggedIn = true;

// ❌ Invalid Names
let user-name;      // Can't use hyphens
let 1stPlace;       // Can't start with number
let class;          // Can't use reserved keywords

// ❌ Bad (but valid) Names
let x = "Alice";    // Not descriptive
let a = 99.99;      // Unclear meaning

Real-World Example: Shopping Cart

const storeName = "TechShop";    // Doesn't change
let cartTotal = 0;               // Changes as items added
let itemCount = 0;               // Increases/decreases

// User adds item
cartTotal = 49.99;
itemCount = 1;

// User adds another
cartTotal = cartTotal + 29.99;   // Now $79.98
itemCount = itemCount + 1;       // Now 2 items

Your Turn: Experiment!

Task: Create variables for your name (const) and age (let), then log them.

Experiments to Try:

  1. Test Mutability: Change a let variable (works!), try changing const (error!)
  2. Undefined: Declare without value: let x; then console.log(x)—what shows?
  3. Type Flexibility: Assign a number, then assign text to same let variable—JavaScript allows it!
  4. Math with Variables: let a = 5; let b = 10; let sum = a + b;
  5. Template Literals: Use ${name} instead of "Hello " + name—cleaner!
javascript
Loading...
Expected Output: Name:
Next (Complete this lesson first)
Functions - Creating Reusable Code