Welcome back. In the previous lesson, you opened the p5.js Web Editor, ran a sketch, and saw how setup() creates the canvas once while draw() keeps the sketch running. You now have an empty dungeon room waiting for game information.
This lesson gives names to that information using variables. By the end, you will be able to declare variables that store numbers, text, and true-or-false game facts, such as health, a player name, or whether a key has been collected. Plan for about 35–40 minutes.
Variables: named storage for your game
A game constantly needs to remember facts:
- the player has 3 health points;
- the player is named "Quest Runner";
- the player has not found the dungeon key yet.
A variable is a named place where JavaScript stores one of those values. The variable’s name tells us what the value means.

For instance:
let playerHealth = 3;
Read this as: “Create a variable called playerHealth and store the number 3 in it.”
This one line has four useful parts:
| Part | Meaning |
|---|---|
let | The JavaScript keyword that declares a variable. |
playerHealth | The variable’s name. |
= | The assignment operator: it stores the value on the right in the variable on the left. |
3 | The starting value. |
The final semicolon ends the instruction. Keep writing semicolons consistently; it makes programs easier to read and prevents some confusing issues when code grows.
A variable is not permanently tied to its first value. playerHealth can later store 2, then 1, and perhaps 0. That changing information is called game state: the current facts of the game at a particular moment.
Before editing your sketch, watch this p5.js-focused explanation. It introduces let, meaningful names, assigning a starting value, and why game variables are commonly placed at the top of a sketch.
2.2: Variables in p5.js (Define Your Own) - p5.js Tutorial
Watch “2.2: Variables in p5.js (Define Your Own)” by The Coding Train. It uses a shape position as an example, but the same idea will store your dungeon game’s health, names, and state.
Watch declaration for let, naming conventions, and restrictions on names. Continue with assignment to see how a variable receives its starting value. Watch using a value to see a variable replace a raw number in a p5.js sketch, then global scope for the important reason game variables belong above setup() and draw().
Add a small set of dungeon variables
Open your Dungeon Starter sketch in the p5.js Web Editor. Replace its contents with this complete version:
// Dungeon game state
let playerName = "Quest Runner";
let playerHealth = 3;
let hasDungeonKey = false;
function setup() {
createCanvas(600, 400);
console.log("Player:", playerName);
console.log("Health:", playerHealth);
console.log("Has key:", hasDungeonKey);
}
function draw() {
background(28, 31, 46);
}
Press Play. The dark room should still appear. Then open the Console at the bottom of the editor. You should see three lines reporting your variable values.
For now, console.log() is simply a way to ask the program to report something in the Console. It is placed in setup() because setup() runs once. If it were in draw(), it would print the same message repeatedly and flood the Console.
Notice that the three let lines are above both functions:
let playerName = "Quest Runner";
let playerHealth = 3;
let hasDungeonKey = false;
This placement makes them global variables. In this course, that means both setup() and draw() can use them later. That matters because a game may set up a player in setup(), then read and change the player’s state while draw() repeats.
Avoid placing a changing piece of game state inside draw():
function draw() {
let playerHealth = 3;
}
That would create a fresh playerHealth variable every time draw() runs. A game could never remember damage from one frame to the next. Keep your main game-state variables at the top of the sketch instead.
Three values your game needs
The examples in your sketch use the three core data types for this lesson.
Numbers
A number stores a quantity. Do not put quotation marks around it.
let playerHealth = 3;
let gold = 25;
let playerSpeed = 4.5;
Numbers are useful for values you may count, compare, move, or calculate later: health, score, position, speed, damage, and enemy count.
The following is a number:
let roomNumber = 4;
But this is text, not a number:
let roomNumber = "4";
They may look similar to a person, but JavaScript treats them differently. A numeric 4 can be used in calculations; the string "4" is a piece of text.
Strings
A string is text. It must be surrounded by quotation marks. You can use either double quotes or single quotes, but use one style consistently.
let playerName = "Quest Runner";
let weaponName = "Bone Sword";
let roomMessage = "Find the dungeon key!";
Without quotation marks, JavaScript assumes Quest Runner is code rather than text. Because it contains a space and is not a defined variable name, it would cause an error.
Strings are ideal for names, dialogue, messages, item labels, and descriptions. A string can contain digits, too:
let saveName = "Dungeon Run 1";
Even though that text contains 1, the whole value is still a string because it is inside quotes.
Booleans
A Boolean stores one of only two values:
true
false
Booleans represent facts that have two possible states. They are especially useful for game rules.
let hasDungeonKey = false;
let isGameOver = false;
let doorIsOpen = true;
Do not put quotation marks around true or false.
let hasDungeonKey = false; // A Boolean
let hasDungeonKeyText = "false"; // A string containing text
Those values are different. The first can later control a game rule. For example, a future conditional can check whether hasDungeonKey is true and allow the player through a locked exit. The second is merely the word “false” written as text.
The names of Boolean variables often begin with words such as is, has, or can. That makes the code read like a question:
isGameOverhasDungeonKeycanOpenDoor
For the moment, just store the Boolean value. You will make the game behave differently based on it in a later lesson.
Choose names JavaScript can understand
Variable names should describe the value they store. This is more important in a game than it may first seem: after your sketch has player movement, enemies, projectiles, and collectibles, playerHealth is far easier to understand than x or thing1.
Use camelCase for names made of several words:
let playerHealth = 3;
let enemySpeed = 2;
let hasDungeonKey = false;
The first word starts lowercase; each later word begins with a capital letter. JavaScript is case-sensitive, so these are different names:
let playerHealth = 3;
let playerhealth = 5;
Use the first style, playerHealth, consistently.
A name must not begin with a number or contain spaces:
let 3health = 3; // Not allowed
let player health = 3; // Not allowed
It also cannot use JavaScript keywords such as let or function.
Read the selected portions of MDN Web Docs for a second explanation of the container idea, declaration and initialization, clear naming, and the three value types. Skip the later material on arrays for now.
Storing the information you need — Variables - MDN Web Docs
Read MDN Web Docs’ “Storing the information you need — Variables.” It reinforces the exact JavaScript vocabulary used in this lesson and explains why quotes matter for text.
Begin in the “What is a variable?” section. Read the container explanation, including the button-click example, to see why a program must remember changing information. Then read the “Initializing a variable” section from initialization. Focus on the distinction between first creating a variable and giving it a value; in your game code, let playerHealth = 3; does both together. Next, in “An aside on variable naming rules,” read from the naming guidance. Finally, in “Variable types,” read the Numbers, Strings, and Booleans subsections. Pay particular attention to numbers and strings, then Boolean values. Stop before “Arrays.”
Change the state, then run again
Return to your sketch and edit only the values on the three variable lines:
let playerName = "Key Seeker";
let playerHealth = 5;
let hasDungeonKey = true;
Press Play and check the Console again. The words after the colon should now match your new values.
This is the practical advantage of variables: you can adjust a game fact in one clear place, rather than searching through the code for every raw number or piece of text. When the sketch restarts, these declarations establish the game’s starting state again:
- a player name;
- a health amount;
- whether the key has already been found.
Leave your code with any values you like, but ensure it still has:
- at least one number variable;
- at least one quoted string variable;
- at least one unquoted
trueorfalseBoolean variable; - all three declarations above
setup().
Key takeaways
A variable gives a useful name to a value the program needs to remember.
- Use
letto declare variables that may change. - A line such as
let playerHealth = 3;declares and initializes a variable in one step. - Numbers such as
3store quantities and do not use quotes. - Strings such as
"Quest Runner"store text and require quotes. - Booleans are exactly
trueorfalse, without quotes, and represent two-state game facts. - Put main game-state variables at the top of a p5.js sketch so both
setup()anddraw()can use them. - Use meaningful camelCase names such as
hasDungeonKeyandplayerHealth.
Next, you will use p5.js drawing functions and canvas coordinates to turn some of these numbers into a visible player and dungeon room.
Can't find a good explanation? Sign up and we'll make it for you
Sign up