What are variables?
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What Are Variables?
Variables are containers that store values. Think of them as labeled boxes where you can keep information.
let starterName = "Aquachu";
console.log(starterName);Here, starterName is a variable storing the text "Aquachu". We can use it throughout our code!
Exercise 2 — Declaring Variables with let
To create a variable in JavaScript, we use the keyword let:
let codemonType = "water";
let niveauPuissance = 75;Variables are named 'variables' because their value can change! Look at that:
let health = 100;
console.log(health);
health = 80; // Changed!
console.log(health);Here, we initially set the variable health to 100, then later changed it to 80.
Exercise 3 — What About var?
Another keyword to create variables is var. You might see it in older JavaScript code:
var oldWay = "This is outdated";
let modernWay = "This is better!";I advise you to always use let instead of var. Why?
- var has confusing scoping rules
- let is more predictable and safer
- Modern JavaScript uses let
Exercise 4 — Which Keyword to Use?
Which keyword should you use to declare a variable in modern JavaScript?
letvarvariabledefineHint : Use the modern way! Avoid var.
Exercise 5 — Create Your First Variable
Complete this code to create a variable:
Hint : Use let to declare, then the variable name, =, and the value.
Exercise 6 — Changing a Variable's Value
You created a variable like this:
let codemonLevel = 5;
Now your Codémon leveled up! Which code correctly changes its level to 6?
codemonLevel = 6;let codemonLevel = 6;codemonLevel == 6;var codemonLevel = 6;Hint : To change a variable's value, just use its name and =. Don't use let again - that would try to create a new variable with the same name!
Exercise 7 — Battle Damage!
Your Aquachu starts with 100 HP, but takes 25 damage in battle. Complete the code:
Exercise 8 — Match Code and Result
Match each code snippet with what it displays:
let power = 50;
console.log(power);let power = 50;
power = 75;
console.log(power);let name = "Aquachu";
console.log(name);let type = "water";
type = "fire";
console.log(type);Exercise 9 — Create Your Codémon
Time to create your own Codémon! Write code to:
1. Create a variable codemonName with your favorite starter (Aquachu, Pyrochu, or Florachu)
2. Create a variable hp starting at 100
3. Your Codémon takes 25 damage in battle (change hp to 75)
4. Display both the name and new HP
// Create your Codémon here