Variables with let and const

A variable gives a value a name so your program can remember it, and let or const says whether that value is allowed to change.

Novice · JavaScript · Updated

After this lesson you can

  • Declare a variable with let or const, and choose which one fits the value
  • Choose a legal, meaningful variable name written in camelCase

Key takeaways

  • A variable is a named value your program remembers. Write let or const, a name, = and the value.
  • Use const for a value that stays the same, and let for a value you'll change later, such as a running total.
  • Giving a const a new value stops the program with a TypeError, so a value you meant to keep can't change by accident.
  • Names use letters, digits, _ and $, can't start with a digit or hold a space, and are written in camelCase.
  • Choose names that say what the value means, such as orderTotal, not x or t.

Every app you use remembers things while you use it: the items in your shopping cart, your score in a game, the stamps on a coffee shop's loyalty card. A program keeps each of those in a variable. You'll write variables in almost every program from here on, starting with The Daily Grind, the neighborhood coffee shop whose order app we're building pieces of in this chapter.

A labeled jar

Behind the counter at The Daily Grind there's a row of jars with labels on them: Tips, Oat milk, Cinnamon. The label is how anyone finds what's inside, without opening every jar.

A variable is a labeled jar for a value: the label is its name, and what's inside is its value. Here is one:

let tipJar = 12;
console.log(tipJar);
12

Read the first line aloud as "let tip jar be 12":

  • let tells JavaScript to make a new variable. Making one is called declaring it.
  • tipJar is the name on the label.
  • = puts the value on its right into the variable on its left. It's called assignment, and it's read "is set to" or "gets". It doesn't ask whether two things are equal; that's a different symbol, in Booleans and Comparisons.
  • 12 is the value, and ; (a semicolon) ends the statement.

console.log(tipJar) prints the value in the jar, not its name.

Changing what's in the jar

A variable made with let can be given a new value. The new value replaces the old one, the way emptying a jar and refilling it does:

let stamps = 3;
console.log(stamps);

stamps = 4;
console.log(stamps);

stamps = stamps + 1;
console.log(stamps);
3
4
5

The last change looks strange in math class, but read it the way JavaScript does: first work out the right side (stamps + 1 is 4 + 1, which is 5), then put that into stamps. That's how a program counts things up.

Notice that let appears only once. let makes the jar; after that you use its name. Writing let stamps a second time stops the program with SyntaxError: Identifier 'stamps' has already been declared.

Try it. In your practice folder, make a file named stamps.js. Declare let stamps = 0;, add 1 to it three times (one visit each), print it after each visit, and run it with node stamps.js.

A jar with a sealed lid: const

Some values shouldn't change while the program runs: the shop's name, or what a latte costs on today's menu board. For those, JavaScript has a jar with a sealed lid, const, short for constant and read "const" or "constant".

const shopName = 'The Daily Grind';
const lattePrice = 4.75;

console.log(shopName);
console.log(lattePrice);
The Daily Grind
4.75

The words in quotes are text, called a string; Strings and Template Literals covers them. A const must get its value on the line that declares it, because once the lid is sealed nothing more goes in.

The error for changing a const

Here is what happens if a line tries to change a const:

const lattePrice = 4.75;
lattePrice = 5.25;
console.log(lattePrice);
TypeError: Assignment to constant variable.

Node stops at the second line and prints the file name, the line number (2), the line itself with a ^ under the spot, and then this message. The console.log never runs. Read the message as it says: you tried to assign a value to a constant. That's JavaScript protecting you: a value you said would stay the same can't be changed by a slip of the keyboard.

let or const?

Ask one question about each value: will this program need to give it a new value later?

The value Changes later? Declare it with
The shop's name No const
Today's price of a latte No const
An order's total, as items are added Yes let
The stamps on a loyalty card, one per visit Yes let

Start with const, and switch to let when a value really must change. Then a reader knows, from the first word, which values move. Here are both together:

const lattePrice = 4.75;
const muffinPrice = 3.25;

let orderTotal = 0;
orderTotal = orderTotal + lattePrice;
orderTotal = orderTotal + muffinPrice;

console.log(orderTotal);
8

In older code and some tutorials you'll also see var, the way variables were declared before 2015. It has confusing rules, and this course uses let and const only.

Names: the rules and camelCase

JavaScript has a few firm rules for names. A name:

  • can use letters, digits, _ (underscore) and $ (dollar sign)
  • can't start with a digit
  • can't hold a space or a hyphen (-)
  • can't be a word JavaScript already uses, such as let, const or if
  • is case-sensitive: lattePrice and LattePrice are two different variables

Beyond the rules there's a habit every JavaScript programmer follows: camelCase. The first word is all lowercase, and every word after it starts with a capital, so the capitals stick up like a camel's humps: orderTotal, stampsOnCard, oatMilkLattePrice.

Legal and clear:     lattePrice   stampsOnCard   orderTotal   tipPercent
Not legal:           latte price  (a space)
                     latte-price  (a hyphen)
                     2ndLatte     (starts with a digit)
                     const        (a word JavaScript uses)
Legal but unclear:   x   p   data   thing

A good name says what the value means, so someone reading your code (including you, next month) doesn't have to guess. x could be anything; tipPercent can only be one thing.

Try it. Make a file named order.js. Declare a const for the price of a cold brew (4.25), a let named orderTotal starting at 0, add two cold brews to the total, and print it. Then try changing the cold brew's price on a later line, run it, and read the error.

Check yourself

2 questions to try on the lesson page.

So what

Every program you write starts by putting values into well-named variables. Choosing const or let tells the next reader which of those values can move, and JavaScript holds you to it.

Key terms

Cheat sheets

Related