CodeStride
Getting Started

Variables: let and const in JavaScript

Topic 2 of 64 · 8 minFree lesson

Programs need to remember things: a score, a name, the price of a coffee. A variable is a name that holds a value, like a labeled box you can put something in and look inside later.

Making a variable with let

The word let makes a new variable. Give it a name, then = and the value to put in it.

Example 1
let score = 10;console.log(score);
10

The = sign here doesn't mean "equals" like in math. It means "put this value in the box". When you use the name later, JavaScript looks inside the box and uses the value.

Changing a value

A variable made with let can change. Write its name, = and the new value. Don't write let again: that would try to make a second box with the same name.

Example 2
let lives = 3;console.log(lives);lives = 2;console.log(lives);
32

You can also use a variable's old value to work out its new one. The right side is worked out first, then the answer goes in the box.

Example 3
let coins = 5;coins = coins + 10;console.log(coins);
15

Values that never change: const

The word const makes a constant: a variable whose value can't be changed later. Use it for things that stay the same, like a name or the number of days in a week.

Example 4
const city = "Lisbon";const daysInWeek = 7;console.log(city, daysInWeek);
Lisbon 7

Working with variables

Variables can hold text or numbers, and you can use them in sums. Good names make the code read almost like a sentence.

Example 5
const price = 4;let quantity = 3;console.log("Total:", price * quantity);
Total: 12

Names can use letters, digits, _ and $, but can't start with a digit. When a name has more than one word, start each new word with a capital, like daysInWeek. This style is called camelCase. Capital letters matter, so score and Score are two different names.

Common mistakeChanging a const. JavaScript refuses and stops with an error. If a value needs to change, make it with let instead.
Example 6
const total = 0;total = total + 5;
TypeError: Assignment to constant variable.
TipStart with const, and switch to let only when the value has to change. Then anyone reading your code knows which values stay put. You may also see the word var in older code. It's the old way to make variables, and let and const replace it.

Try it yourself

Run the code in the editor and answer 8 practice questions on variables: let and const. It's free, you only need an account.