Real JavaScript Variables
Build a basketball game with JavaScript variables. Store team names, scores, fouls, the period, and possession, then run the code to bring the scoreboard to life.
What is a variable?
A variable is like a labeled box. You write a name on the outside, put a value inside, and close the lid. From then on, whenever your code uses the name on the label, the computer opens the box and grabs whatever is inside. The label stays the same — but you can swap what's in the box any time.
-
1
Make the box:
let homeTeam = "Comets";lettells JavaScript "make a new box."homeTeamis the label you write on it.=means "put this inside," and"Comets"is the value that goes in the box. -
2
Use the label, get what's inside
say(homeTeam)displays Comets — not "homeTeam." There are no quotes around it, so the computer knows it's a box label and opens the box to find the value. -
3
Why coders use them
Variables let a program remember things — a player's name, a score, a team name. And if your home team's name appears 20 times in a game, you only change the box once and every spot updates. Try it: change
homeTeamorhomeScoreand run the code again.
Code a basketball scoreboard.
Choose values for your game. Each choice becomes a real JavaScript variable.
Change the controls or edit the generated code below. Press Run Code to start the game.
Basketball game
02:18
COMETS
ROCKETS
42
39
3
3
4
◀
Press Run Code!
- Run your code to see output.
Type real JavaScript, then run it.
You stored basketball game data in variables and used it to control the scoreboard.
Open Variable Builder