Skip to content
wannacode

Variables and types

Problem

The price is in three places

In an online shop one price shows up in several places: in the catalog, in the cart and at checkout. If it is written as a number everywhere, here is what happens:

console.log("Headphones: €49.90");
console.log("In the cart: headphones, €49.90");
console.log("To pay: €49.90");

Tomorrow the headphones are on sale. You have to find and fix every 49.90. Miss one, and the customer sees two different prices.

The idea

A variable: a name for a value

Write the price once and give it a name. Then write the name everywhere.

const price = 49.90;
console.log("Headphones: €" + price);
console.log("In the cart: headphones, €" + price);
console.log("To pay: €" + price);
Output
Headphones: €49.9
In the cart: headphones, €49.9
To pay: €49.9

const price = 49.90; creates a variable: a name (price) under which the program keeps a value (49.90). Wherever the code says price, the program takes the value from there. const means the value will not change. For a value that changes there is let: you will see it in a moment. You do not write the type: JavaScript sees it from the value.

+ between text and a value glues them into one text. That is why the spaces are inside the quotes.

The zero at the end disappeared: 49.90 came out as 49.9. For the number it is the same thing. You will see how to show the price with two digits after the decimal point in the lesson on input and output.

More precisely, if you are curious
  • A name starts with a letter and has no spaces. Write it in lowercase, and start each next word with a capital letter: price, pricePerNight. Uppercase and lowercase letters matter: price and Price are two different names.
  • The language also allows names with letters outside English (café), but do not do it. Code all over the world uses plain Latin names, and that is how your colleagues will write too.
  • A name that was not created with const or let stops the program with ReferenceError: price is not defined. let total; without a value is allowed: then total holds undefined, "no value".

The idea

Kinds of values

The type says what the variable can hold. Here are the main ones:

const name = "Backpack";
const price = 39.90;
const stock = 12;
const onSale = true;
const size = "M";
console.log(name + ", size " + size);
console.log("Price: €" + price);
console.log("In stock: " + stock + " items");
console.log("On sale: " + onSale);
Output
Backpack, size M
Price: €39.9
In stock: 12 items
On sale: true
  • number: any number, whole or decimal: a count, a price, a weight. In code the decimal separator is a point: 39.90. JavaScript has no separate type for whole numbers.
  • boolean: yes or no, true or false.
  • string: text, in quotes: "Backpack". This is a string, a sequence of characters. There is no separate type for one character: "M" is text of length 1.

typeof tells you the type of a value. If you add these lines to the same program:

console.log(typeof name);
console.log(typeof price);
console.log(typeof stock);
console.log(typeof onSale);
console.log(typeof size);
Output
string
number
number
boolean
string
More precisely, if you are curious

number is a decimal number in 8 bytes, like double in Java and C#. Whole numbers in it are exact up to Number.MAX_SAFE_INTEGER, 9,007,199,254,740,991. After that, not every whole number can be stored, and 9007199254740993 becomes ...992. For bigger whole numbers there is a separate type, BigInt: a number with n at the end. Underscores between digits only make it easier to read:

const population = 8_100_000_000;
const weight = 1.5;
console.log(population + " " + weight);
console.log(Number.MAX_SAFE_INTEGER);
console.log(9007199254740993);
console.log(9007199254740993n);
Output
8100000000 1.5
9007199254740991
9007199254740992
9007199254740993n

number stores numbers in binary, and some decimal values like 0.1 do not come out exactly: 0.1 + 0.2 is 0.30000000000000004. That is why real programs keep money in whole cents. In this course, to keep it short, we write prices as number.

Try it

Find the bug

The program should print one purchase. It does not start: Node.js says SyntaxError. Which line is the bug on?

Pick the line with the bug.

The idea

= stores a copy

The = sign is not "equals" as in math. It means: take the value on the right and store it in the variable on the left. This is called assignment. The variable's old value is gone.

When there is another variable on the right, a copy of its value at that moment is stored. The two variables do not stay connected:

let seats = 40;
const seatsAtStart = seats;
seats = 37;
console.log("At the start: " + seatsAtStart);
console.log("Now: " + seats);
Output
At the start: 40
Now: 37

seatsAtStart gets 40. Then seats becomes 37, but the copy in seatsAtStart stays 40.

seats uses let, because its value changes. seatsAtStart uses const: it only remembers the start.

Try it

Which value stays?

What will the program print?

let roomA = 12;
let roomB = 20;
roomA = roomB;
roomB = 25;
console.log(roomA + " and " + roomB);
Answer

Problem

The sizes are swapped

A photo printing program gets the sizes swapped: width 120 and height 80, when they should be 80 x 120. It looks like you just need to store one in the other and back again:

let width = 120;
let height = 80;
width = height;
height = width;
console.log(width + " x " + height);
Output
80 x 80

You got 80 x 80. Where did 120 go?

See it

Swapping with a helper variable

let width = 120;
let height = 80;
const temp = width;
width = height;
height = temp;
console.log(width + " x " + height); // 80 x 120
Step by step, in words
  1. The width and the height were entered swapped: 120 and 80.
  2. temp = width: a copy of 120 goes into temp. width still holds 120.
  3. width = height: a copy of 80 goes into width. The old 120 is gone from there, but it is saved in temp.
  4. height = temp: 120 comes back from temp into height.
  5. They are swapped: 80 x 120.

In the naive version, width = height stores 80 in width, and the old 120 is gone. When height = width comes next, width already holds 80, and that is copied back.

The fix is a third, helper variable, temp. It keeps 120 before width is overwritten. Then 120 goes from temp into height, and the sizes come out 80 x 120.

More precisely, if you are curious
In JavaScript the swap can also be written on one line. On the right, both values are collected in an array, and only then are they stored on the left:
let width = 120;
let height = 80;
[width, height] = [height, width];
console.log(width + " x " + height);
Output
80 x 120

You will see it in other people's code. Here we write it with temp, so you can see what happens step by step.

Try it

Put the swap in order

At the shop, two coworkers trade shifts. morning is "Ivan", and evening is "Maria". Put the lines in order so they swap.

  1. evening = temp;
  2. console.log("Morning: " + morning + ", evening: " + evening);
  3. const temp = morning;
  4. morning = evening;

The idea

The type belongs to the value

In JavaScript you do not write the type of the variable. It belongs to the value: 3 is a number, "three" is a string. That is why a variable with let can later get a value of another type:

let nights = 3;
console.log(typeof nights);
nights = "three";
console.log(typeof nights);
Output
number
string

JavaScript does not complain. This is called dynamic typing: the type is known only while the program runs. It is handy, but it also easily leads to bugs. Keep one kind of value in one variable.

const protects against something else: the value cannot be changed at all, not to another type and not to the same type:

const nights = 3;
nights = 4;
Message from Node.js
TypeError: Assignment to constant variable.

So write const, and let only when the value really changes.

More precisely, if you are curious

In old code you will see var instead of let. It works a little differently, and new code does not use it.

Exercise

Your variables

Solve the tasks in your editor. The values are written in the code, with no reading from the keyboard. Reading is in the next lesson.

1. Swap. The top shelf has 15 books, the bottom one 27. Store them in two variables, swap their values and print before and after.

Output
Before: top 15, bottom 27
After: top 27, bottom 15

2. Age. Store a name and an age in two variables and print them in a sentence.

Output
Maria is 19 years old.

3. A hotel card. Store in variables the name of the hotel (text), the stars (a whole number), the rating (a decimal), whether there is breakfast (yes or no) and the category (one character). Print them.

Output
Hotel: Sea Star
Stars: 4
Rating: 8.7
Breakfast: true
Category: B

More tasks

  • Three in a circle. Three cash registers start the day with €120, €85 and €240. Move the amounts in a circle: the first goes into the second, the second into the third, the third into the first. Use one helper variable. Print 240 120 85.
  • The types. Print the type of each value from task 3 with typeof.
  • An error on purpose. Change the value of a const later in the program and read what Node.js says. Then write the rating with a comma, const rating = 8,7;.

Test

Check yourself

1. What does the line let count = 5; do?
2. What is the type of 12.99 in JavaScript?
3. let a = 5; const b = a; a = 9; What is b?
4. Why does swapping two values need a third variable?
5. const nights = 3; and then nights = 4;. What happens?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·