🌱 Growing Every Day β€” Early access. New content drops regularly!

content

Variables

Variables description goes here.

What Is a Variable?

A variable is a named container that stores a value. Think of it as a labelled box where you can put information, retrieve it later, and even swap it out for something new.

In everyday life, you use "variables" all the time:

  • Your age changes every year, but the label "my age" stays the same
  • The current temperature updates constantly, but we still call it "the temperature"
  • Your shopping cart total changes as you add items, but it's always "the total"

In JavaScript, we create variables to store data like numbers, text, lists, and much more.

[IMAGE PLACEHOLDER: "Variable as Labelled Box"

DESCRIPTION: A friendly illustration showing three labelled boxes/containers on a shelf:

  • Box labelled "username" containing the text "frontend-dev"
  • Box labelled "score" containing the number 42
  • Box labelled "isLoggedIn" containing a checkmark (representing true)

Each box has a small icon indicating its type (text icon, number icon, boolean icon).

An arrow points to one box with the caption: "The label is the variable NAME" Another arrow points inside the box: "The contents are the variable VALUE"

STYLE: Clean, modern illustration. Consistent with TRTD brand colours. Approachable and non-intimidating. Could include a small character "placing" a value into a box.]


Creating Your First Variable

In JavaScript, you create a variable using a keyword followed by the name you want to give it. Let's start with let:

let username;

This creates a variable called username. Right now, it's emptyβ€”like an empty labelled box.

To put a value inside, we use the assignment operator (=):

let username;
username = "frontend-dev";

Or, more commonly, we do both in one line:

let username = "frontend-dev";

Now we can use this variable anywhere in our code:

let username = "frontend-dev";
console.log(username); // Output: frontend-dev
console.log("Hello, " + username); // Output: Hello, frontend-dev

[VIDEO PLACEHOLDER: "Creating and Using Variables" β€” 2-3 minutes

CONTENT: Screen recording with instructor picture-in-picture.

  1. Start with empty VS Code / code editor
  2. Type let username; β€” explain "let" is the keyword, "username" is our chosen name
  3. Show that console.log(username) outputs undefined (the box exists but is empty)
  4. Add username = "frontend-dev"; β€” explain the = sign means "assign this value"
  5. Show console.log(username) now outputs "frontend-dev"
  6. Combine into one line: let username = "frontend-dev";
  7. Create a few more variables: let age = 25; and let isStudent = true;
  8. Show using variables in console.log with string concatenation
  9. Briefly show the browser console output

KEY MOMENTS:

  • Pause when explaining "undefined" β€” this is a common confusion point
  • Highlight that = means "assign" not "equals" in programming
  • Show the instant feedback of console.log

STYLE: Calm pace, clear pronunciation of code, highlight/zoom on important parts. Friendly tone.]


Loading editor...

The Three Declaration Keywords

JavaScript gives you three ways to declare variables: let, const, and var. Each behaves slightly differently.

let β€” The Modern Default

Use let when you need a variable whose value might change later.

let score = 0;
score = 10; // βœ“ This works fine
score = 25; // βœ“ Can change as many times as needed

const β€” For Values That Don't Change

Use const (short for "constant") when the value should never be reassigned.

const PI = 3.14159;
PI = 3; // βœ— Error! Cannot reassign a const
const USERNAME = "frontend-dev";
USERNAME = "new_name"; // βœ— Error!

const is great for:

  • Configuration values that shouldn't change
  • References to HTML elements
  • Values that are truly constant (like PI)

var β€” The Old Way (Avoid It)

var is the original way to declare variables in JavaScript. You'll see it in older code, but we recommend using let and const instead.

var oldSchool = "from the past";

Why avoid var? It has some confusing behaviours around "scope" (where variables are accessible) that can lead to bugs. We'll cover this in a later lesson, but for now, just remember: use let or const.

[IMAGE PLACEHOLDER: "let vs const vs var Comparison"

DESCRIPTION: A visual comparison table/infographic:

KeywordCan Reassign?When to UseStatus
letβœ“ YesValues that changeβœ“ Modern, recommended
constβœ— NoValues that stay fixedβœ“ Modern, recommended
varβœ“ YesAvoid in new code⚠️ Legacy, not recommended

Below the table, a simple decision flowchart: "Will this value ever need to change?"

  • Yes β†’ Use let
  • No β†’ Use const
  • "What about var?" β†’ Arrow pointing to "Don't worry about it for now"

STYLE: Clean, scannable. Use green checkmarks and red X marks. Highlight the recommended options. Make it "screenshot-worthy" for student notes.]


See It In Action

Experiment with variables in the interactive editor below. Try changing values and see what happens!

[INTERACTIVE COMPONENT: "Variable Playground"

TYPE: Sandpack code editor with live preview/console

LAYOUT:

  • Left panel: Code editor
  • Right panel: Console output (showing console.log results)

STARTING CODE:

// Try changing these values!
let playerName = "Hero";
let health = 100;
const maxHealth = 100;
console.log("Player: " + playerName);
console.log("Health: " + health + "/" + maxHealth);
// Try uncommenting the line below - what happens?
// maxHealth = 150;
// Experiment: Create your own variables below!

FEATURES:

  • Real-time execution as user types (debounced)
  • Console output panel showing results
  • Clear error messages for mistakes (e.g., "TypeError: Assignment to constant variable")
  • "Reset Code" button to restore starting code
  • Line numbers in editor
  • Syntax highlighting

GUIDED CHALLENGES (displayed as collapsible hints):

  1. "Change the playerName to your own name"
  2. "Reduce the health by 20 (set it to 80)"
  3. "Uncomment line 9 and observe the error"
  4. "Create a new variable called level with a value of 1"

DESIGN: Dark theme editor (like VS Code dark), clear console output, friendly error formatting]


Knowledge Check

[INTERACTIVE COMPONENT: "Quick Understanding Check"

TYPE: Single multiple-choice question

QUESTION: "You're creating a variable to store a user's current score in a game. The score will increase as they play. Which declaration should you use?"

_____ score = 0;

OPTIONS:

  • A) const β€” because it's a number
  • B) let β€” because the value will change βœ“
  • C) var β€” because it's a score variable
  • D) Any of them would work fine

FEEDBACK:

  • Correct (B): "Exactly! Since the score will change during gameplay, let is the right choice. const would prevent us from updating it, and we avoid var in modern code."
  • Incorrect: Shows explanation of why the correct answer is B, with a brief reinforcement of the let vs const decision.

DESIGN: Clean card layout, immediate feedback, encouraging tone]


Naming Your Variables

Variable names (also called identifiers) must follow certain rules in JavaScript:

The Rules (Must Follow)

  1. Can contain letters, numbers, underscores (_), and dollar signs ($)
  2. Must start with a letter, underscore, or dollar sign (not a number)
  3. Cannot be a reserved word (like let, const, if, function)
  4. Are case-sensitive (score, Score, and SCORE are three different variables)
// βœ“ Valid names
let userName = "alex";
let user_name = "alex";
let $price = 9.99;
let _private = "hidden";
let player1 = "Hero";
// βœ— Invalid names
let 1player = "Hero"; // Can't start with number
let user-name = "alex"; // Can't use hyphens
let let = "value"; // Can't use reserved words

The Conventions (Best Practices)

While JavaScript allows many naming styles, the community has agreed on camelCase for variables:

// βœ“ camelCase (recommended)
let firstName = "Alex";
let numberOfItems = 5;
let isLoggedIn = true;
let maxHealthPoints = 100;
// βœ— Other styles (avoid for variables)
let first_name = "Alex"; // snake_case - used in Python, not JS
let FirstName = "Alex"; // PascalCase - reserved for classes
let FIRST_NAME = "Alex"; // SCREAMING_CASE - reserved for true constants

Make Names Meaningful

Good variable names describe what they contain:

// βœ— Unclear
let x = "alex@email.com";
let n = 42;
let flag = true;
// βœ“ Clear and descriptive
let userEmail = "alex@email.com";
let itemCount = 42;
let isSubscribed = true;

[IMAGE PLACEHOLDER: "Variable Naming Guide"

DESCRIPTION: A visual "dos and don'ts" guide:

LEFT SIDE β€” "Do This βœ“":

  • firstName with annotation "camelCase"
  • totalPrice with annotation "descriptive"
  • isActive with annotation "boolean prefix"
  • itemCount with annotation "indicates number"

RIGHT SIDE β€” "Avoid This βœ—":

  • x with annotation "too vague"
  • first_name with annotation "wrong convention"
  • data with annotation "not specific"
  • myVariable with annotation "meaningless"

BOTTOM: Quick reference for camelCase: "first word lowercase, then Capitalize Each Word" Examples: firstName, numberOfItems, isUserLoggedIn

STYLE: Clean two-column layout, clear visual distinction between good and bad examples, colour-coded (green for good, red for bad)]


Reassigning Variables

One of the most common operations is changing a variable's value:

let score = 0;
console.log(score); // 0
score = 10;
console.log(score); // 10
score = score + 5; // Take current value, add 5, store result
console.log(score); // 15

Notice that when reassigning, we don't use let againβ€”the variable already exists:

let score = 0;
let score = 10; // βœ— Error! score is already declared
// Correct way:
let score = 0;
score = 10; // βœ“ Just reassign without 'let'

Shorthand Operators

JavaScript provides shortcuts for common operations:

let count = 10;
// Long way
count = count + 1; // 11
// Shorthand
count += 1; // Same as count = count + 1
count -= 3; // Same as count = count - 3
count *= 2; // Same as count = count * 2
count /= 4; // Same as count = count / 4
// Even shorter (for adding/subtracting 1)
count++; // Same as count = count + 1
count--; // Same as count = count - 1

[VIDEO PLACEHOLDER: "Reassigning Variables & Shorthand Operators" β€” 2 minutes

CONTENT: Screen recording demonstrating:

  1. Create let score = 0; and log it
  2. Reassign with score = 10; and log it
  3. Show the error when trying to re-declare with let score = 10;
  4. Demonstrate score = score + 5; explaining "it reads the current value, adds 5, then stores the result back"
  5. Introduce += shorthand: "This does the same thing in less typing"
  6. Quick demo of -=, *=, /=
  7. Show ++ and -- for incrementing/decrementing by 1
  8. Practical example: Building a simple counter

KEY EMPHASIS:

  • Don't use let twice for the same variable
  • The shorthand operators are just convenience, they do the same thing

STYLE: Clear code highlighting, show before/after values, include console output]


Practice: Variable Reassignment

Use the code editor to practice reassigning variables and using shorthand operators.

[INTERACTIVE COMPONENT: "Reassignment Practice"

TYPE: Sandpack editor with guided tasks

STARTING CODE:

let lives = 3;
let score = 0;
const pointsPerCoin = 10;
console.log("Starting game...");
console.log("Lives:", lives);
console.log("Score:", score);
// TASK 1: The player collected a coin!
// Add pointsPerCoin to the score using +=
// TASK 2: The player collected another coin!
// Add pointsPerCoin again
// TASK 3: The player got hit!
// Decrease lives by 1 using --
// TASK 4: Log the final stats
console.log("--- FINAL STATS ---");
// Add console.log statements for lives and score

EXPECTED OUTPUT (shown as goal):

Starting game...
Lives: 3
Score: 0
--- FINAL STATS ---
Lives: 2
Score: 20

FEATURES:

  • Task completion detection (checks if output matches expected)
  • Hint button for each task
  • "Check Solution" reveals answer
  • Success animation when all tasks complete

HINTS:

  1. "Use score += pointsPerCoin; to add points"
  2. "Same as task 1!"
  3. "Use lives--; to decrease by 1"
  4. "Use console.log like the examples above"

SOLUTION:

// TASK 1
score += pointsPerCoin;
// TASK 2
score += pointsPerCoin;
// TASK 3
lives--;
// TASK 4
console.log("Lives:", lives);
console.log("Score:", score);
```]
---
## Common Mistakes to Avoid
### Mistake 1: Trying to reassign a `const`
```javascript
const API_KEY = "abc123";
API_KEY = "xyz789"; // βœ— TypeError: Assignment to constant variable

Fix: If you need to change the value later, use let instead.

Mistake 2: Re-declaring a variable with let

let username = "alex";
let username = "jordan"; // βœ— SyntaxError: Identifier 'username' has already been declared

Fix: Remove the second let:

let username = "alex";
username = "jordan"; // βœ“ Works!

Mistake 3: Using a variable before declaring it

console.log(score); // βœ— ReferenceError: score is not defined
let score = 100;

Fix: Always declare variables before using them:

let score = 100;
console.log(score); // βœ“ Works!

Mistake 4: Forgetting that variable names are case-sensitive

let userName = "alex";
console.log(username); // βœ— ReferenceError: username is not defined

Fix: Use the exact same capitalisation:

let userName = "alex";
console.log(userName); // βœ“ Works!

[IMAGE PLACEHOLDER: "Common Variable Errors"

DESCRIPTION: A visual error guide showing 4 error scenarios:

For each error:

  • The problematic code snippet
  • The actual error message (styled like browser console)
  • A "βœ“ Fix" showing the corrected code

Layout: 2x2 grid of error cards, each clearly showing the problem and solution.

Possible design element: A friendly "bug" character pointing out each mistake.

STYLE: Code snippets in monospace font, error messages in red, fixes in green. Educational, not intimidatingβ€”normalise that errors happen!]


Knowledge Check

[INTERACTIVE COMPONENT: "Variable Mastery Quiz"

TYPE: 3-question quiz with varied formats

QUESTION 1 (Multiple Choice): "What will this code output?"

let x = 5;
x += 3;
x *= 2;
console.log(x);
  • A) 5
  • B) 8
  • C) 16 βœ“
  • D) 11

Explanation: x starts at 5, then becomes 8 (5+3), then becomes 16 (8Γ—2).

QUESTION 2 (Fill in the Blank): "Complete the code to create a constant called MAX_LEVEL with a value of 50:"

_______ MAX_LEVEL = 50;

Answer: const

QUESTION 3 (True/False): "The following code will cause an error:"

let count = 1;
let count = 2;
  • True βœ“
  • False

Explanation: You cannot re-declare a variable with let. Remove the second let to reassign the value.

FEATURES:

  • Progress indicator
  • Immediate feedback per question
  • Score summary at end
  • Option to retry missed questions]

Summary

[IMAGE PLACEHOLDER: "JavaScript Variables Cheat Sheet"

DESCRIPTION: A comprehensive, "screenshot-worthy" reference card containing:

SECTION 1 β€” Declaration Keywords:

let β†’ Can change, modern βœ“
const β†’ Cannot change, modern βœ“
var β†’ Avoid in new code ⚠️

SECTION 2 β€” Naming Rules:

  • Start with letter, _, or $
  • Can contain letters, numbers, _, $
  • Cannot use reserved words
  • Case-sensitive

SECTION 3 β€” Naming Convention: camelCase for variables Examples: firstName, isActive, totalCount

SECTION 4 β€” Common Operations:

let x = 10; // Declare & assign
x = 20; // Reassign
x += 5; // Add and assign (x = x + 5)
x -= 3; // Subtract and assign
x++; // Increment by 1
x--; // Decrement by 1

SECTION 5 β€” Quick Decision: Will it change? β†’ let Will it stay fixed? β†’ const

STYLE: Single-page reference card design. TRTD branding. Print-friendly (works in black & white). Clear visual hierarchy. QR code linking to this lesson optional.]


Key Takeaways:

  1. Variables are named containers that store values in your program

  2. Use let for values that will change, const for values that won't

  3. Avoid var in new code β€” it's legacy and has confusing behaviour

  4. Follow camelCase naming: firstName, totalScore, isComplete

  5. Reassign variables without repeating the keyword: score = 10; not let score = 10;

  6. Use shorthand operators for cleaner code: +=, -=, ++, --


Exercises

Complete these exercises to solidify your understanding. Try each one before revealing the solution!


Exercise 1: Player Profile

Create variables to represent a player in a video game:

  1. A constant for the player's username: "DragonSlayer99"
  2. A variable for their current level: 1
  3. A variable for their experience points (XP): 0
  4. A constant for the XP needed per level: 100
  5. Log a message: "DragonSlayer99 is level 1 with 0/100 XP"

[INTERACTIVE COMPONENT: "Sandpack Exercise β€” Player Profile"

STARTING CODE:

// Create your variables here:
// Log the player profile:
console.log(/* your message here */);

EXPECTED OUTPUT:

DragonSlayer99 is level 1 with 0/100 XP

HINTS:

  • "Which values will change as the player progresses? Use let for those."
  • "Which values are fixed? Use const for those."
  • "You can combine variables with strings using + or template literals"

SOLUTION:

const username = "DragonSlayer99";
let level = 1;
let xp = 0;
const xpPerLevel = 100;
console.log(username + " is level " + level + " with " + xp + "/" + xpPerLevel + " XP");
// Or using template literals (preview of future lesson):
// console.log(`${username} is level ${level} with ${xp}/${xpPerLevel} XP`);
```]
---
### Exercise 2: Shopping Cart
Simulate adding items to a shopping cart:
1. Start with `totalItems = 0` and `totalPrice = 0`
2. Add 3 items at $9.99 each (update both variables)
3. Add 1 item at $24.99
4. Log the final totals
[INTERACTIVE COMPONENT: "Sandpack Exercise β€” Shopping Cart"
STARTING CODE:
```javascript
let totalItems = 0;
let totalPrice = 0;
// Add 3 items at $9.99 each
// Add 1 item at $24.99
// Log the results
console.log("Items in cart:", totalItems);
console.log("Total price: $", totalPrice);

EXPECTED OUTPUT:

Items in cart: 4
Total price: $ 54.96

HINTS:

  • "To add 3 items, you can use totalItems += 3"
  • "For the price, calculate 3 Γ— 9.99"

SOLUTION:

let totalItems = 0;
let totalPrice = 0;
// Add 3 items at $9.99 each
totalItems += 3;
totalPrice += 3 * 9.99;
// Add 1 item at $24.99
totalItems += 1;
totalPrice += 24.99;
console.log("Items in cart:", totalItems);
console.log("Total price: $", totalPrice);
```]
---
### Exercise 3: Debug the Code
The following code has several bugs. Find and fix them all:
[INTERACTIVE COMPONENT: "Sandpack Debug Exercise"
STARTING CODE (with bugs):
```javascript
const score = 0;
let playerName = "alex"
let PlayerName = "jordan";
score = 100;
console.log(playername + " scored " + score + " points!");
let score = 200;

BUGS TO FIX:

  1. score is declared as const but reassigned
  2. playerName vs PlayerName inconsistency
  3. playername (lowercase) doesn't match the declared variable
  4. Re-declaration of score with let

HINTS (progressive):

  1. "Look at how score is declared vs how it's used"
  2. "Check the capitalisation of player name variables"
  3. "Is there a variable being declared twice?"

SOLUTION:

let score = 0;
let playerName = "alex";
// Removed: let PlayerName = "jordan"; (inconsistent naming)
score = 100;
console.log(playerName + " scored " + score + " points!");
score = 200; // Removed 'let' β€” just reassignment

EXPECTED OUTPUT:

alex scored 100 points!
```]
---
### Exercise 4: Temperature Converter (Challenge)
Create a program that converts Celsius to Fahrenheit:
1. Store a temperature in Celsius (e.g., 25)
2. Convert it to Fahrenheit using the formula: `F = (C Γ— 9/5) + 32`
3. Log both temperatures
[INTERACTIVE COMPONENT: "Sandpack Challenge Exercise"
STARTING CODE:
```javascript
// Store temperature in Celsius
// Convert to Fahrenheit (formula: F = C Γ— 9/5 + 32)
// Log both temperatures
// Expected format: "25Β°C = 77Β°F"

HINT: "Create a const for Celsius (it's your input), and a const for Fahrenheit (calculated from the formula)"

SOLUTION:

const celsius = 25;
const fahrenheit = (celsius * 9) / 5 + 32;
console.log(celsius + "Β°C = " + fahrenheit + "Β°F");

BONUS CHALLENGE: "Try with different values: What is 0Β°C in Fahrenheit? What is 100Β°C?"]


Exercise 5: Open Challenge β€” Build Something!

Using what you've learned, create variables for any scenario you choose:

Ideas:

  • A recipe (ingredient amounts, servings)
  • A social media post (content, likes, shares)
  • A workout tracker (exercise, sets, reps)
  • A book/movie (title, rating, year)

Be creative! Practice using both let and const appropriately.

[INTERACTIVE COMPONENT: "Open Sandbox"

STARTING CODE:

// Your creative project here!
// Use let for values that change
// Use const for values that stay fixed
// Example structure to get you started:
// const projectName = "My Creation";
// let someValue = 0;
// ...

FEATURES:

  • No validation/expected output β€” open-ended creativity
  • "Share Your Code" button (posts to community forum, optional feature)
  • Inspiration gallery showing examples from other students (optional feature)

DESIGN: Encouraging message: "There's no wrong answer here β€” just practice!"]


Additional Resources

Official Documentation

Video Tutorials

Practice Platforms

Deeper Learning


What's Next?

Now that you can store data in variables, you need to know about the different types of data JavaScript can work with. In the next lesson, you'll learn about Data Types β€” strings, numbers, booleans, and more β€” and how to work with each one.

[NAVIGATION COMPONENT:

PREVIOUS LESSON: ← "Your First JavaScript Program" (subtle link/button)

NEXT LESSON: "Data Types in JavaScript" β†’ (prominent button with arrow)

MODULE PROGRESS: Visual progress bar showing "Lesson 3 of 24 complete" List of module lessons with checkmarks for completed ones]


Lesson Feedback

[INTERACTIVE COMPONENT: "Lesson Feedback Widget"

ELEMENTS:

  1. RATING:

    • "How helpful was this lesson?"
    • 5-star clickable rating
    • Current average rating shown after submission
  2. WRITTEN FEEDBACK (collapsed by default):

    • "What could we improve?"
    • Text area (optional)
    • Character count indicator
  3. COMPLETION:

    • Checkbox: "☐ Mark this lesson as complete"
    • When checked: adds to user's progress, updates module progress bar
  4. SUBMIT BUTTON:

    • On submit: Thank you message, optional prompt to continue to next lesson
  5. SHARE OPTION:

    • "Share your progress" β€” generates social media card showing lesson completion

DESIGN: Clean, non-intrusive. Appears naturally at the end of content. Completion checkbox is prominent.]


Lesson Version: 1.0
Last Updated: January 2026
Author: TRTD Content Team
Reviewer: [Peer reviewer name]

Found an error? Have a suggestion? Report it here β€” we read every piece of feedback!


Template Notes for Content Creators

Note: This section is for internal use and should be removed from the published lesson.

Lesson Structure Checklist

  • Front matter complete (course, module, time, difficulty, prerequisites)
  • 3-5 clear learning objectives
  • Hook video (30-45 seconds)
  • Warm-up quiz (3 questions from previous lessons)
  • Core content broken into digestible sections
  • Mix of explanations, code examples, images, and videos
  • Interactive sandbox component for experimentation
  • Knowledge check(s) mid-lesson
  • Practical "Try It Yourself" exercise with Sandpack
  • Common mistakes section (3-5 mistakes)
  • Visual summary/cheat sheet
  • 5-6 key takeaways
  • 4-5 exercises (graduated difficulty)
  • Additional resources (docs, videos, practice)
  • Navigation to prev/next lessons
  • Feedback widget
  • Version info and error reporting link

Content Guidelines

Tone: Friendly, encouraging, never condescending. Assume intelligence, not knowledge.

Code Examples:

  • Short, focused examples (3-10 lines ideal)
  • Always include comments explaining what's happening
  • Show both incorrect and correct approaches where helpful

Images:

  • Every image needs alt text for accessibility
  • Use consistent illustration style across lessons
  • Aim for 1 key image per major concept

Videos:

  • Hook: 30-45 seconds max
  • Concept demos: 2-3 minutes max
  • Never exceed 5 minutes per video
  • Always include captions

Interactive Components:

  • At minimum: 1 playground + 1 knowledge check + exercises
  • Progressive hints before showing solutions
  • Celebrate success (confetti, encouraging messages)

Placeholder Format

For images: [IMAGE PLACEHOLDER: "Title" followed by DESCRIPTION, STYLE notes]

For videos: [VIDEO PLACEHOLDER: "Title" β€” duration, followed by CONTENT breakdown, STYLE notes]

For interactive components: [INTERACTIVE COMPONENT: "Title" followed by TYPE, FEATURES, STARTING CODE, EXPECTED OUTPUT, etc.]

Lesson Complete!

Great job! You've finished this lesson. Ready to continue?