Storing Things in Variables

Using let and const to remember values

8 min read · runnable Javascript

So far we have printed messages directly. But often you want the computer to remember a piece of information so you can use it again later. For that we use a variable.

A variable is like a labelled box. You put a value inside it and give the box a name. Whenever you say the name, you get back what is inside.

Making a variable with let

let name = "Sam";
console.log(name);

Reading that out loud: create a box called name, and put the text "Sam" inside it. Then print whatever is in name.

The = sign here does not mean equals like in maths. It means put the value on the right into the box on the left.

let vs const

There are two main words for making variables:

  • let creates a box whose contents you can change later.
  • const creates a box whose contents stay the same forever. (const is short for constant, meaning unchanging.)
let score = 10;
score = 20; // allowed, score can change

const birthday = "July";
// birthday = "May"; // this would cause an error
Tip: Use const by default. Only reach for let when you know the value needs to change. This makes your programs safer and easier to read.

Try it yourself

Run the code, then try changing the value of score or adding your own variable.

Try it yourself
Output
Press “Run code” to see the result.

Quick check

Q1 Which keyword should you use for a value that will never change?

Q2 In let score = 10; what does the = sign do?

Want to save your progress? It's free.

Create a free account