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 city with let and 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, change lives to 2.

  • Print lives again.

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 const called daysInWeek set to 7.

  • 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.

  • lives needs to change, so change const to let on 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 const called playerName with any name in quotes, and a let called score set to 0.

  • Add 10 points: set score to score + 10.

  • Print playerName and score in one console.log.

More in JavaScript Basics

Previous: Hello, World! · Next: Strings and Numbers