Variables
Programming Languages · JavaScript Basics · 10 min
Store values in named boxes with let and const, and change them when you need to.
A box with a name
A variable is a named box that holds a value. Make one with let, a name, = and the value. After that, use the name to get the value back.
let pet = "cat";
console.log(pet); // cat
No quotes around pet when you use it: quotes would print the word itself.
Create a variable
citywithletand set it to"Lisbon".Print
city(the variable, not the word in quotes).
Changing a let
A let variable can change. Give it a new value with =, without writing let again (let is only for creating it).
let mood = "sleepy";
mood = "awake";
console.log(mood); // awake
Below the first
console.log, changelivesto2.Print
livesagain.
Values that stay put: const
const also makes a variable, but its value can never be replaced. Use it for things that shouldn't change, like the number of days in a week.
const hoursInDay = 24;
console.log(hoursInDay);
Create a
constcalleddaysInWeekset to7.Print
daysInWeek.
Why const?
If you try to change a const, JavaScript stops with an error. That's a good thing: it catches mistakes early.
So the rule is simple: use const by default, and let only when the value needs to change.
The code on the right crashes. Run it and read the error first.
livesneeds to change, so changeconsttoleton the first line.
Put it together: a game score
console.log can print several things at once: separate them with commas and it puts a space between them.
const fruit = "kiwi";
console.log(fruit, 3); // kiwi 3
Now build a tiny scorekeeper. Pick which variables are const and which are let.
Create a
constcalledplayerNamewith any name in quotes, and aletcalledscoreset to0.Add 10 points: set
scoretoscore + 10.Print
playerNameandscorein oneconsole.log.
More in JavaScript Basics
Previous: Hello, World! · Next: Strings and Numbers