Here's how you create a variable in JavaScript:
let age = 25;
console.log(age);
It prints
25
Let's take this apart, piece by piece:
| Piece | What it means |
|---|---|
let | "Hey JavaScript, I want a new box." This is called a keyword. |
age | The label on the box: the variable's name |
= | "Put this value into the box" |
25 | The value going into the box |
; | End of statement |
So let age = 25; reads like: "Make a new box, label it age, and put 25 inside."
Then console.log(age) says: "Look inside the box labeled age and print what you find." Notice there are no quotes around age. If you write console.log("age") with quotes, you'll just print the word "age". No quotes means "use the variable."
let age = 25;
console.log("age");
console.log(age);
It prints
age 25
The equals sign is not "equals"
This is the single most important thing to understand in Grade 1, so we're putting it in big letters:
In JavaScript, = means "put into," not "is equal to."
In math class, x = 5 is a statement of fact: x and 5 are the same. In JavaScript, x = 5 is an action: take the value 5 and put it into the box called x. Programmers call this assignment. When reading code out loud, many people say "gets": "age gets 25."
(JavaScript does have a way to check whether two things are equal, but it uses a different symbol. You'll meet it in Grade 3.)
Changing what's in the box
The whole point of a variable is that it can vary. (That's literally where the name comes from.) You can swap out the value in the box any time you like:
let mood = "sleepy";
console.log(mood);
mood = "excited";
console.log(mood);
mood = "hungry";
console.log(mood);
It prints
sleepy excited hungry
Notice that we only use let the first time, when we create the box. After that, we just use the name. The box already exists, so we're simply replacing what's inside it. The old value gets thrown out and the new value takes its place.
If you use let again with the same name, JavaScript gets upset, because you're trying to create a box that already exists:
let mood = "sleepy";
let mood = "excited";
It stops with an error
Uncaught SyntaxError: Identifier 'mood' has already been declared
"Identifier" is just the fancy word for a variable's name. To change a variable, drop the let the second time: mood = "excited";
Lots of boxes
You can have as many variables as you like, and they can hold all kinds of values. Text goes in quotes, numbers don't:
let firstName = "Mia";
let city = "Lisbon";
let shoeSize = 39;
let favoriteNumber = 7;
console.log(firstName);
console.log(city);
console.log(shoeSize);
console.log(favoriteNumber);
It prints
Mia Lisbon 39 7
You can also print several things at once by separating them with commas inside console.log. They'll be printed on one line with spaces in between:
let firstName = "Mia";
let city = "Lisbon";
console.log(firstName, "lives in", city);
It prints
Mia lives in Lisbon