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-devconsole.log("Hello, " + username); // Output: Hello, frontend-dev[VIDEO PLACEHOLDER: "Creating and Using Variables" β 2-3 minutes
CONTENT: Screen recording with instructor picture-in-picture.
- Start with empty VS Code / code editor
- Type
let username;β explain "let" is the keyword, "username" is our chosen name - Show that
console.log(username)outputsundefined(the box exists but is empty) - Add
username = "frontend-dev";β explain the = sign means "assign this value" - Show
console.log(username)now outputs "frontend-dev" - Combine into one line:
let username = "frontend-dev"; - Create a few more variables:
let age = 25;andlet isStudent = true; - Show using variables in console.log with string concatenation
- 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.]
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 finescore = 25; // β Can change as many times as neededconst β 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:
| Keyword | Can Reassign? | When to Use | Status |
|---|---|---|---|
| let | β Yes | Values that change | β Modern, recommended |
| const | β No | Values that stay fixed | β Modern, recommended |
| var | β Yes | Avoid 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):
- "Change the playerName to your own name"
- "Reduce the health by 20 (set it to 80)"
- "Uncomment line 9 and observe the error"
- "Create a new variable called
levelwith 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,
letis the right choice.constwould prevent us from updating it, and we avoidvarin modern code." - Incorrect: Shows explanation of why the correct answer is B, with a brief reinforcement of the
letvsconstdecision.
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)
- Can contain letters, numbers, underscores (
_), and dollar signs ($) - Must start with a letter, underscore, or dollar sign (not a number)
- Cannot be a reserved word (like
let,const,if,function) - Are case-sensitive (
score,Score, andSCOREare three different variables)
// β Valid nameslet userName = "alex";let user_name = "alex";let $price = 9.99;let _private = "hidden";let player1 = "Hero";
// β Invalid nameslet 1player = "Hero"; // Can't start with numberlet user-name = "alex"; // Can't use hyphenslet let = "value"; // Can't use reserved wordsThe 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 JSlet FirstName = "Alex"; // PascalCase - reserved for classeslet FIRST_NAME = "Alex"; // SCREAMING_CASE - reserved for true constantsMake Names Meaningful
Good variable names describe what they contain:
// β Unclearlet x = "alex@email.com";let n = 42;let flag = true;
// β Clear and descriptivelet 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 β":
firstNamewith annotation "camelCase"totalPricewith annotation "descriptive"isActivewith annotation "boolean prefix"itemCountwith annotation "indicates number"
RIGHT SIDE β "Avoid This β":
xwith annotation "too vague"first_namewith annotation "wrong convention"datawith annotation "not specific"myVariablewith 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 resultconsole.log(score); // 15Notice 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 waycount = count + 1; // 11
// Shorthandcount += 1; // Same as count = count + 1count -= 3; // Same as count = count - 3count *= 2; // Same as count = count * 2count /= 4; // Same as count = count / 4
// Even shorter (for adding/subtracting 1)count++; // Same as count = count + 1count--; // Same as count = count - 1[VIDEO PLACEHOLDER: "Reassigning Variables & Shorthand Operators" β 2 minutes
CONTENT: Screen recording demonstrating:
- Create
let score = 0;and log it - Reassign with
score = 10;and log it - Show the error when trying to re-declare with
let score = 10; - Demonstrate
score = score + 5;explaining "it reads the current value, adds 5, then stores the result back" - Introduce
+=shorthand: "This does the same thing in less typing" - Quick demo of
-=,*=,/= - Show
++and--for incrementing/decrementing by 1 - Practical example: Building a simple counter
KEY EMPHASIS:
- Don't use
lettwice 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 statsconsole.log("--- FINAL STATS ---");// Add console.log statements for lives and scoreEXPECTED OUTPUT (shown as goal):
Starting game...Lives: 3Score: 0--- FINAL STATS ---Lives: 2Score: 20FEATURES:
- Task completion detection (checks if output matches expected)
- Hint button for each task
- "Check Solution" reveals answer
- Success animation when all tasks complete
HINTS:
- "Use
score += pointsPerCoin;to add points" - "Same as task 1!"
- "Use
lives--;to decrease by 1" - "Use console.log like the examples above"
SOLUTION:
// TASK 1score += pointsPerCoin;
// TASK 2score += pointsPerCoin;
// TASK 3lives--;
// TASK 4console.log("Lives:", lives);console.log("Score:", score);```]
---
## Common Mistakes to Avoid
### Mistake 1: Trying to reassign a `const`
```javascriptconst API_KEY = "abc123";API_KEY = "xyz789"; // β TypeError: Assignment to constant variableFix: 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 declaredFix: 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 definedlet 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 definedFix: 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 & assignx = 20; // Reassignx += 5; // Add and assign (x = x + 5)x -= 3; // Subtract and assignx++; // Increment by 1x--; // Decrement by 1SECTION 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:
-
Variables are named containers that store values in your program
-
Use
letfor values that will change,constfor values that won't -
Avoid
varin new code β it's legacy and has confusing behaviour -
Follow camelCase naming:
firstName,totalScore,isComplete -
Reassign variables without repeating the keyword:
score = 10;notlet score = 10; -
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:
- A constant for the player's username:
"DragonSlayer99" - A variable for their current level:
1 - A variable for their experience points (XP):
0 - A constant for the XP needed per level:
100 - 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 XPHINTS:
- "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.994. Log the final totals
[INTERACTIVE COMPONENT: "Sandpack Exercise β Shopping Cart"
STARTING CODE:```javascriptlet totalItems = 0;let totalPrice = 0;
// Add 3 items at $9.99 each
// Add 1 item at $24.99
// Log the resultsconsole.log("Items in cart:", totalItems);console.log("Total price: $", totalPrice);EXPECTED OUTPUT:
Items in cart: 4Total price: $ 54.96HINTS:
- "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 eachtotalItems += 3;totalPrice += 3 * 9.99;
// Add 1 item at $24.99totalItems += 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):```javascriptconst score = 0;let playerName = "alex"let PlayerName = "jordan";
score = 100;console.log(playername + " scored " + score + " points!");
let score = 200;BUGS TO FIX:
scoreis declared asconstbut reassignedplayerNamevsPlayerNameinconsistencyplayername(lowercase) doesn't match the declared variable- Re-declaration of
scorewithlet
HINTS (progressive):
- "Look at how score is declared vs how it's used"
- "Check the capitalisation of player name variables"
- "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 reassignmentEXPECTED 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
- MDN: let β Complete reference for the
letkeyword - MDN: const β Complete reference for the
constkeyword - MDN: JavaScript Data Types β What kinds of values variables can hold (preview of next lesson!)
Video Tutorials
- JavaScript Variables Explained (Fireship) β Fast-paced 5-minute overview
- var vs let vs const (Web Dev Simplified) β Deep dive into the differences
Practice Platforms
- JavaScript.info: Variables β Alternative explanation with exercises
- freeCodeCamp JavaScript Course β Extended practice challenges
Deeper Learning
- Why const Doesn't Mean Immutable β Advanced concept for when you're ready
- Temporal Dead Zone Explained β Why
letandconstbehave differently thanvar
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:
-
RATING:
- "How helpful was this lesson?"
- 5-star clickable rating
- Current average rating shown after submission
-
WRITTEN FEEDBACK (collapsed by default):
- "What could we improve?"
- Text area (optional)
- Character count indicator
-
COMPLETION:
- Checkbox: "β Mark this lesson as complete"
- When checked: adds to user's progress, updates module progress bar
-
SUBMIT BUTTON:
- On submit: Thank you message, optional prompt to continue to next lesson
-
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?