CodeRigor

LESSON

Name values with variables

Store numbers and text under names with const and let, calculate with them and put the results into printed lines.

The programs in the last lesson could only print text that you had typed in advance. To calculate anything, a program has to remember things: a price, a count, a name. This lesson shows how.

A variable is a name for a value

A value is a piece of data, such as the number 4 or the text "notebook". A variable is a name that refers to a value, so that later statements can use the value by name.

You create a variable with the word const, a name, an equals sign, then the value. Creating a variable is called declaring it.

JavaScript
const price = 4;
console.log(price);

This prints 4. Notice that price has no quotation marks. console.log("price") would print the word price; console.log(price) prints the value that the name refers to.

In JavaScript, = does not mean "is equal to" as it does in maths. It means "this name refers to this value". Read const price = 4; as "price is the name for 4".

Numbers and text

Every value has a type, which says what kind of data it is. You need two types for now:

Type JavaScript's name Examples
number, whole or with a decimal point number 3, 0, -12, 2.5
text (string) string "notebook", "3"

A whole number is also called an integer. JavaScript uses the one type number for integers and for numbers with a decimal point.

The quotation marks matter: 3 is a number you can do arithmetic with, and "3" is a piece of text that happens to contain a digit.

Arithmetic

JavaScript calculates with the symbols below, which are called operators.

JavaScript
console.log(7 + 2);   // add
console.log(7 - 2);   // subtract
console.log(7 * 2);   // multiply
console.log(7 / 2);   // divide
console.log(7 % 2);   // the remainder after dividing

This prints 9, 5, 14, 3.5 and 1, one per line.

Two details are worth remembering:

  • A whole result is printed without a decimal point: 10 / 5 prints 2.
  • Multiplication and division happen before addition and subtraction, as in maths. 2 + 3 * 4 is 14. Use round brackets to choose a different order: (2 + 3) * 4 is 20.

A piece of program text that produces a value, such as 7 + 2 or price * 3, is called an expression.

const stays, let can change

A name declared with const refers to the same value for as long as the program runs. When a value has to change later, such as a count that goes up, declare the name with let instead. After that, an assignment gives the name a new value: write the name, an equals sign and the new value, without repeating let.

JavaScript
const price = 4;
let quantity = 3;
const total = price * quantity;
console.log(total);
quantity = 5;
console.log(total);

This prints 12 and then 12 again. JavaScript works out the right-hand side of = first, then makes the name on the left refer to the result. Step through the diagram to see why the second line of output is not 20.

What each name refers to, line by line
start / 6 ⇄ code
total was given the value 12 when line 3 ran. Changing quantity later does not go back and recalculate it.
What each name refers to, line by line
total was given the value 12 when line 3 ran. Changing quantity later does not go back and recalculate it.

A variable does not remember how its value was calculated. It refers to the finished result.

The new value may be calculated from the old one:

JavaScript
let count = 7;
count = count + 1;
console.log(count);
count += 1;
console.log(count);

This prints 8 and then 9. As a maths equation, count = count + 1 would be nonsense. As an instruction it is ordinary: "work out count + 1, then call the answer count". count += 1 is a shorter way to write the same instruction.

How one assignment statement runs
start / 3
JavaScript finishes the right-hand side before it touches the name on the left. That is why count = count + 1 makes sense: the old value is used first, then the name moves to the new value.
How one assignment statement runs
JavaScript finishes the right-hand side before it touches the name on the left. That is why count = count + 1 makes sense: the old value is used first, then the name moves to the new value.

Which word should you choose? Use const by default, and let only for a name whose value really changes. A reader who sees const knows at once that the value stays the same. Older JavaScript had a third word, var, which you will see in old examples. It has confusing rules, and this unit never uses it.

Choosing names

A variable name may contain letters, digits and underscores (_). It may not start with a digit, and it may not contain spaces. Capital letters count, so total and Total are two different names.

JavaScript programmers join the words of a name and give each word after the first a capital letter: unitPrice, firstName. Choose names that say what the value means. price is better than p, and far better than x.

Putting values into printed text

console.log accepts several arguments separated by commas. It prints them on one line with a space between each.

JavaScript
const item = "notebook";
const quantity = 3;
console.log("Item:", item);
console.log(quantity, "of them");

This prints Item: notebook and 3 of them.

When you want full control of the spacing, use a template literal: a string written between backticks (`) instead of quotation marks. Inside a template literal, ${ } with an expression between the curly brackets is replaced by the value of that expression.

JavaScript
const item = "notebook";
const price = 2.5;
console.log(`One ${item} costs ${price} pounds.`);
console.log(`Two cost ${price * 2} pounds.`);
console.log(`Price: ${price.toFixed(2)}`);

This prints One notebook costs 2.5 pounds., Two cost 5 pounds. and Price: 2.50. Writing .toFixed(2) after a number produces text that shows the number with exactly two digits after the decimal point, which is what you want for money.

The backtick is a different key from the quotation mark; on many keyboards it is at the top left. With ordinary quotation marks nothing is replaced: console.log("Costs ${price}") prints Costs ${price}, dollar sign and brackets included.

There is a second reason to use .toFixed(2). Computers store numbers with a decimal point in a way that cannot represent every decimal exactly, so tiny errors appear:

JavaScript
console.log(0.1 + 0.2);
console.log((0.1 + 0.2).toFixed(2));

This prints 0.30000000000000004 and then 0.30. The first line is not a fault in your program; it is how such numbers behave in almost every programming language. Round the number when you display it.

Two errors you will meet

A misspelt variable name. JavaScript only knows the names you have declared.

JavaScript
const total = 12;
console.log(totl);
Text
/work/main.js:2
console.log(totl);
            ^

ReferenceError: totl is not defined
    at Object.<anonymous> (/work/main.js:2:13)

ReferenceError means an unknown name, and the message quotes it. The first line says line 2, and the ^ points at the name. The fix is to spell the name the way it was declared.

Assigning to a const name.

JavaScript
const count = 7;
count = count + 1;
console.log(count);
Text
/work/main.js:2
count = count + 1;
      ^

TypeError: Assignment to constant variable.
    at Object.<anonymous> (/work/main.js:2:7)

TypeError means an operation was used on a value or name that does not allow it. Here the message says it in plain words: line 2 assigns to a constant, which is a name declared with const. If the value is meant to change, declare the name with let on line 1. If it is not, line 2 is the mistake.

What you can do now

You can give values names with const and let, calculate with numbers, update a variable, and build lines of output from text and values. In the exercises you will predict what assignments and calculations print, then write a program that works out and prints a receipt.

Next: read what the user types, so that the values can come from the person running the program.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Starts at chapter 2, 'Variables' (12:32), about thirteen minutes. Chapter 3, 'Arithmetic operators' (25:20), and chapter 6, 'Constants' (44:48), cover the rest of this lesson. The course is taught with a web page; the JavaScript is the same in Node.