What is a variable?
In programming, we use variables to store information. By storing values in variables, we can use and change that information all through a program. Say we make a game where the player has a certain number of lives. We can use a variable to store the number of lives.
We start by creating a variable, which is called declaring it. In JavaScript, you declare a variable with the keyword let:
let numLives;
Right now, numLives is an empty storage container. If we want to give it a starting value, we can also initialize the variable when we declare it:
let numLives = 3;
Now say the player loses a life and has 2 lives left. We change the value of a variable by assigning a different value to it:
numLives = 2;
Notice how we do not use the keyword let when assigning a new value to an existing variable. That's because we aren't creating a new variable. We just want to change the value inside the one we already have.
What if a value should never change? JavaScript has a second keyword for that: const (short for constant). Use const for values that stay the same forever, like const maxLives = 3;. If your program tries to reassign it, JavaScript stops you with an error.
Good to know: in older JavaScript code you'll often see var used to declare variables. It still works, but modern JavaScript uses let and const instead.
The program below puts all of this together. Run it and think about these questions:
- What happens when you assign different values to the variable numLives?
- Say the player loses another life. Could you add a line that assigns a new value to numLives?
- Look at the last line. What's the difference between the variable and the text in quotes? What would happen to the printed output if you changed the value of numLives?
// Initializes a variable to store the number of lives let numLives = 3; console.log(numLives); /* After the player loses a life, assigns a new value to the numLives variable */ numLives = 2; console.log(numLives); // You can print variables and text together console.log("You have " + numLives + " lives left.");
3 2 You have 2 lives left.
Sandbox: let vs const
Here are two variables living side by side. One was declared with let, the other with const. Press each button to try reassigning them and watch what JavaScript does:
A let variable is happy to change. Go ahead!
A const variable is locked in. Try it anyway!
Why does JavaScript do this? A const is a promise that the value will never change. If some other line of code tries to break that promise, JavaScript throws a TypeError instead of silently changing it. That protects you from sneaky bugs.
Naming variables
When naming variables in JavaScript, follow these rules:
- No spaces
- Must start with a letter, $, or _ (not a number)
- Variable names are case sensitive: score and Score are two different variables!
- Written in lower camelCase: the first word starts with a lowercase letter, and every word after that starts with a capital letter, like numLives or playerScore
One more tip that isn't exactly a rule: name your variable so it describes the information it's holding. numLives tells you way more than x, and it makes your program much easier to read and understand.
Type a name below and the checker will tell you if JavaScript would accept it:
- No spaces
- Doesn't start with a number
- Only letters, numbers,
$, and_ - Not a reserved word (like
let,var,function, orclass)
Practice: Mandalorian rescue
Stormtrooper Countdown
The Mandalorian is about to escape with Baby Yoda when he is ambushed by 15 stormtroopers! He uses a variety of attacks to defeat them. Create a program that uses a variable to keep track of the remaining stormtroopers. After each attack, change the value of the variable and print the number of remaining stormtroopers with console.log.
The Mandalorian starts by using his blaster to knock out 5 stormtroopers. Then, he uses his flamethrower to knock out 3 more. With 7 left, the Mandalorian uses his Amban rifle to get 3 out of the way. Finally, he goes in for hand-to-hand combat to finish off the last 4 stormtroopers! With stormtroopers littered around the room, the Mandalorian is free to escape with Baby Yoda!
When run, your program should look like this:
There are 10 stormtroopers left. There are 7 stormtroopers left. There are 4 stormtroopers left. There are 0 stormtroopers left.
Hint: look at the last line of the Variable Basics example when writing your print statements. You can glue text and a variable together with +.
// Store the number of stormtroopers let numStormtroopers = 15; // Blaster takes out 5 numStormtroopers = numStormtroopers - 5; console.log("There are " + numStormtroopers + " stormtroopers left."); // Flamethrower takes out 3 numStormtroopers = numStormtroopers - 3; console.log("There are " + numStormtroopers + " stormtroopers left."); // Amban rifle takes out 3 numStormtroopers = numStormtroopers - 3; console.log("There are " + numStormtroopers + " stormtroopers left."); // Hand-to-hand combat finishes the last 4 numStormtroopers = numStormtroopers - 4; console.log("There are " + numStormtroopers + " stormtroopers left.");
There are 10 stormtroopers left. There are 7 stormtroopers left. There are 4 stormtroopers left. There are 0 stormtroopers left.
Types of variables
So far we've only stored numbers. But variables can hold other kinds of information too! The variable's type is based on the kind of data it holds. These are the core types in JavaScript:
Any number: whole numbers like -5, 0, and 15, or decimals like 43.67 and -0.11. Unlike some languages, JavaScript uses one type for both.
let numLives = 3;
Text. Strings are always surrounded by quotes.
const name = "Baby Yoda";
Either true or false. Great for yes-or-no facts.
let isJedi = true;
Take a look at this example to see the types in action, then think about these questions:
- Can you identify the type of each variable?
- Notice how the boolean value true has no quotes around it. If you added quotes, what type would it become?
- Could you change the type of age by assigning it a different value?
// The child's name never changes, so const fits perfectly const name = "Baby Yoda"; console.log("The child's name is " + name); let age = 140.6778; console.log("The child is " + age + " years old."); let isJedi = true; console.log("Is the child a Jedi? " + isJedi);
The child's name is Baby Yoda The child is 140.6778 years old. Is the child a Jedi? true
Practice: weapon upgrade
Mandalorian, Round Two
Extend your program from Practice 1 to include a variable that stores the type of weapon the Mandalorian uses for each attack. That means you'll need two variables: one for the remaining number of stormtroopers (a number) and one for the weapon (a string). Print four statements describing each phase of the attack, and be sure to change the value of both variables before printing each line!
Here's what a run of your program should print:
The Mandalorian uses his blaster to attack. There are 10 stormtroopers left. The Mandalorian uses his flamethrower to attack. There are 7 stormtroopers left. The Mandalorian uses his Amban rifle to attack. There are 4 stormtroopers left. The Mandalorian uses his hands to attack. There are 0 stormtroopers left.
As a reminder: the blaster knocks out 5, the flamethrower knocks out 3, the Amban rifle gets 3 out of the way, and hand-to-hand combat finishes off the last 4.
// One number variable and one string variable let numStormtroopers = 15; let weapon = "blaster"; numStormtroopers = numStormtroopers - 5; console.log("The Mandalorian uses his " + weapon + " to attack. There are " + numStormtroopers + " stormtroopers left."); weapon = "flamethrower"; numStormtroopers = numStormtroopers - 3; console.log("The Mandalorian uses his " + weapon + " to attack. There are " + numStormtroopers + " stormtroopers left."); weapon = "Amban rifle"; numStormtroopers = numStormtroopers - 3; console.log("The Mandalorian uses his " + weapon + " to attack. There are " + numStormtroopers + " stormtroopers left."); weapon = "hands"; numStormtroopers = numStormtroopers - 4; console.log("The Mandalorian uses his " + weapon + " to attack. There are " + numStormtroopers + " stormtroopers left.");
The Mandalorian uses his blaster to attack. There are 10 stormtroopers left. The Mandalorian uses his flamethrower to attack. There are 7 stormtroopers left. The Mandalorian uses his Amban rifle to attack. There are 4 stormtroopers left. The Mandalorian uses his hands to attack. There are 0 stormtroopers left.
The power of variables
So far, we've changed the values of variables and printed them to the console. But variables are much more powerful than that! This final example uses the CodeHS JavaScript graphics library to draw a circle inside of a square, and one variable controls the size of both shapes:
let radius = 100; let side = radius * 2; drawSquare(); drawCircle(); // Draws a circle function drawCircle() { let circle = new Circle(radius); circle.setPosition(getWidth() / 2, getHeight() / 2); circle.setColor(Color.blue); add(circle); } // Draws a square function drawSquare() { let square = new Rectangle(side, side); square.setPosition(getWidth() / 2 - radius, getHeight() / 2 - radius); square.setColor(Color.orange); add(square); }
// a blue circle drawn inside an orange square
How is the variable radius used in this program? What would happen if you changed its value? Try it yourself. Drag the slider to reassign radius and watch both shapes resize together:
One assignment changes every place the variable is used: the circle's size, the square's size, and where the square sits. That's the power of variables!
If we had not used a variable for the radius, we'd have to update the size in multiple places every time we wanted to change it, which gets super tricky when you have hundreds and hundreds of lines of code!
In conclusion, the power of variables comes from their ability to store information that we can use throughout our program, making it easy to update our programs as we work.
A JavaScript variables example
JavaScript variables use let and const. This program stores values and prints them to the console.
Quick quiz
1. Which line correctly creates a variable whose value can change later?
2. What does this program print?
let lives = 3; lives = 1; console.log(lives);
3. Which of these is a legal JavaScript variable name written in good camelCase style?
Keep learning JavaScript
Variables are the memory of every program you'll ever write. Next, learn how to fill them with whatever the user types, and how to make decisions based on what they hold.