Constants
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Constants with const
Sometimes you want a variable that never changes. For this, use const (short for "constant"):
const maxCodemonInTeam = 6;
const gameName = "Codémon Adventure";
console.log(maxCodemonInTeam);
console.log(gameName);These values won't change during your program - they're constant!
Exercise 2 — When to Use const vs let
Once you create a const, you cannot change it. Try uncommenting the last line and run the code:
App limitation
On mobile, the following example won't show an error message when you try to reassign a const. However, if you run the same code on a computer, you'll see an error in the console.
const starter = "Aquachu";
console.log(starter);
// starter = "Pyrochu"; // Uncomment this line to see the error!Now let's compare const and let:
const vs let
const → Values that never change
• Game settings: const maxLevel = 100;
• Fixed data: const gameName = "Codémon";
let → Values that will change
• Counters: let score = 0;
• Health: let hp = 100;
Exercise 3 — Which Keyword Should You Use?
What happens if you try to change a const variable?
Hint : Remember: const exists to protect a value from being modified. How would JavaScript react to enforce that protection?
Exercise 4 — Which Keyword Should You Use?
You're storing the name of your game, which will never change. Which should you use?
const gameName = "Codémon";let gameName = "Codémon";var gameName = "Codémon";Hint : If the value never changes, use const. If it will change, use let!
Exercise 5 — Create a Constant
Complete this code to create a constant for the maximum team size:
Hint : If the value never changes, use const. If it will change, use let!
Exercise 6 — const or let?
You're tracking a Codémon's health that will decrease during battles. Which should you use?
let health = 100;const health = 100;var health = 100;Hint : Health will change during battles, so you need a variable that can be updated!
Exercise 7 — Build Your Team
Create a Codémon team management system!
1. Create a const called teamName with your team's name
2. Create a const called maxTeamSize set to 6
3. Create a let variable currentTeamSize starting at 1 (just your starter)
4. Add 2 more Codémon to your team (change currentTeamSize to 3)
5. Display the team name, max size, and current size
// Build your team here