Leet School

{module 5}

Values and variables

Your first JavaScript20 min read

What you will be able to do

  • Store numbers, text and true or false in variables, with const and let.
  • Build a line of text from values with a template literal.
  • Turn what a visitor typed into a number with Number(), and recognise NaN when it appears.

Why it matters

Muscat Dates sells boxes of dates from a shop in Muscat, Oman. Every order gets one extra box free. Salim, the owner, asked his nephew Faisal for an order page that tells customers what they pay and how many boxes they receive. On the first day a customer typed 3 and read "You receive 31 boxes". She phoned the shop to ask whether it was a mistake. Two other customers did not phone, and did not order.

The arithmetic in Faisal's script was right. The problem was the kind of value it worked with: the page gave him the text "3", not the number 3. This lesson is about the kinds of values a script holds, and how to turn one into another.

The idea

Values and their types

A value is one piece of data. You will use three kinds of value in this module.

  • A number: 12, 3, 0. Numbers have no quotes.
  • A string: a piece of text, inside quotes. "Khalas" is a string, and so is "12".
  • A boolean: true or false, with no quotes. It answers a yes or no question.

The kind of a value is called its type, and typeof tells you the type of a value. The next file, values.js, prints a few values in the Console. Given several values with commas between them, console.log prints them on one line.

values.js
console.log(typeof 12, typeof "12", typeof true);
console.log("3" + 1);
console.log(Number("3") + 1);
console.log(Number("3 boxes"));
console.log(Number(""));
console.log(Number.isNaN(Number("3 boxes")));

A small page, values.html, runs the script with the same kind of script element as in lesson 1:

values.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Values</title>
    <script src="values.js" defer></script>
  </head>
  <body>
    <p>Open the Console.</p>
  </body>
</html>

Open the page and look in the Console:

Output
number string boolean
31
4
NaN
0
true

The rest of this section explains each line.

Variables, with const and let

A variable is a name for a value. You made two in lesson 1. You create one with const, a name, = and a value:

From order.js
const boxPriceDollars = 12;

Read = as "is set to". From now on, boxPriceDollars means 12. A name has no spaces and does not start with a digit. When it has several words, each word after the first starts with a capital letter. The name says what the value is, and here also its unit: dollars.

const means the variable can never be given another value. Most values in a script should not change, and const stops you from changing one by mistake. When a value must change, create it with let:

From order.js
let totalDollars = boxes * boxPriceDollars;
totalDollars = totalDollars + deliveryDollars;

The first line sets the total to the price of the boxes. The second line takes the total, adds the delivery, and stores the result under the same name. You write let only the first time. Use const unless you know that a value will change.

Text built from values

A template literal is a string written between backticks, the ` key, which on many keyboards is at the top left. Inside it, ${...} is replaced by a value:

From order.js
summary.textContent = `Total for ${boxes} boxes with delivery: $${totalDollars}. You receive ${boxesReceived} boxes.`;

Look at $${totalDollars}. The first $ is an ordinary dollar sign that the customer sees. The second starts ${, which is replaced by the total. A long line built this way reads more clearly than one joined with +, as in lesson 1.

What a field gives you

The value of a field is always a string, even in a field with type="number". When the customer types 3, the script receives "3".

With a string, + joins text. That is the second line of the Console: "3" + 1 gives 31, the mistake from "Why it matters". The * sign has no meaning for text, so JavaScript turns both sides into numbers first. That is why quantityField.value * 18 worked in lesson 1.

Number() turns a string into a number. Number("3") + 1 gives 4. Turn every value from a field into a number before you do arithmetic with it.

NaN: not a number

When Number() cannot read the text as a number, it gives a special value called NaN, short for "not a number". Number("3 boxes") is NaN. NaN spreads: any arithmetic with it gives NaN again, so one NaN early in a script turns every later result into NaN.

Number.isNaN() asks whether a value is NaN, and answers with a boolean. That is the last line of the Console: true.

One case is easy to miss. Number("") gives 0, not NaN. An empty field becomes 0. Lesson 4 shows how to stop a page from treating "nothing typed" as "zero".

Worked example

Make a new folder and create index.html, styles.css and order.js in it, as in lesson 1. Save each file.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Order dates, Muscat Dates</title>
    <link rel="stylesheet" href="styles.css" />
    <script src="order.js" defer></script>
  </head>
  <body>
    <main>
      <h1>Muscat Dates</h1>
      <p>A box of Khalas dates costs $12. Delivery is $3. Every order gets one extra box free.</p>
      <label for="boxes">How many boxes?</label>
      <input type="number" id="boxes" value="2" />
      <p id="summary">Total for 2 boxes with delivery: $27. You receive 3 boxes.</p>
    </main>
  </body>
</html>
styles.css
body {
  max-width: 40rem;
  margin: 0 auto;
  padding: 1rem;
  font-family: Arial, sans-serif;
  line-height: 1.5;
}

#summary {
  font-weight: bold;
}
order.js
const boxPriceDollars = 12;
const deliveryDollars = 3;
const boxesField = document.querySelector("#boxes");
const summary = document.querySelector("#summary");

function showOrder() {
  const boxes = Number(boxesField.value);
  const boxesReceived = boxes + 1;
  let totalDollars = boxes * boxPriceDollars;
  totalDollars = totalDollars + deliveryDollars;
  summary.textContent = `Total for ${boxes} boxes with delivery: $${totalDollars}. You receive ${boxesReceived} boxes.`;
  console.log(typeof boxesField.value, typeof boxes, Number.isNaN(boxes));
}

boxesField.addEventListener("input", showOrder);

Open the page and the Console. Change the number of boxes to 5. The summary reads:

Output
Total for 5 boxes with delivery: $63. You receive 6 boxes.

The Console shows the line from line 12:

Output
string number false

The field gave a string. After Number(), boxes is a number, and it is not NaN.

Read order.js from the top. Lines 1 and 2 are the prices. They are at the top, with names, so that nobody has to search the code for a 12 when the price changes. Lines 3 and 4 find the field and the summary.

Inside the function, line 7 turns what was typed into a number. Line 8 adds the free box. Lines 9 and 10 build the total in two steps, which is why totalDollars uses let. Line 11 writes the summary with a template literal.

Now delete everything in the field:

Output
Total for 0 boxes with delivery: $3. You receive 1 boxes.

The empty field became 0, and the page offers a free box for an order of nothing. Remember this page. Lesson 4 fixes it.

Common mistakes

Leaving out Number()

Line 7 of this version has no Number():

From no-number.js
const boxes = boxesField.value;

Type 5:

Output
Total for 5 boxes with delivery: $63. You receive 51 boxes.

There is no error. The total is right, because * turned "5" into a number. But boxes + 1 joined "5" and 1 as text. When one result is right and another is wrong in the same line, check the type of each value with typeof.

Giving a const a new value

reassign.js
const boxPriceDollars = 12;
const deliveryDollars = 3;
const boxesField = document.querySelector("#boxes");
const summary = document.querySelector("#summary");

function showOrder() {
  const boxes = Number(boxesField.value);
  const boxesReceived = boxes + 1;
  const totalDollars = boxes * boxPriceDollars;
  totalDollars = totalDollars + deliveryDollars;
  summary.textContent = `Total for ${boxes} boxes with delivery: $${totalDollars}. You receive ${boxesReceived} boxes.`;
}

boxesField.addEventListener("input", showOrder);

Type 5. The summary does not change, and the Console shows an error:

Output
Total for 2 boxes with delivery: $27. You receive 3 boxes.
page error: Uncaught TypeError: Assignment to constant variable.

"Assignment" means giving a variable a value. Line 9 made totalDollars with const, and line 10 tries to give it a new one. In your browser the line number appears beside the message, reassign.js:10. The error happens each time you type, not when the page opens, because the line is inside the listener. Change const to let on line 9.

A misspelt property

From misspelt.js
const boxes = Number(boxesField.valu);

Type 5:

Output
Total for NaN boxes with delivery: $NaN. You receive NaN boxes.

There is no error. A field has no property called valu, so JavaScript gives undefined, its value for "nothing here". Number(undefined) is NaN, and the NaN spread to every number on the line. When you see NaN, go back to the first line that made it, and check each name letter by letter.

Think it through

Tomás wants a page for a juice stand. A visitor types how many cups they want, at $2 a cup, and sees "4 cups cost $8". He asks what will happen when the field is empty.

Understand. In: the text of one field. Out: one line built from the number of cups and the price. The odd input is an empty field.

Break down. Read the field. Turn the text into a number. Work out the cost. Build the line.

Plan. A const for the price at the top. Inside the listener, Number() on the value, the cost as cups times price, and a template literal for the line.

Build. He writes the listener with only console.log(typeof cups, cups) in it, and types 4. The Console shows number 4, so the conversion works. Then he adds the line.

Test. 4 gives "4 cups cost $8". He empties the field and reads "0 cups cost $0", which is true but not useful. Then he types -1 and reads "-1 cups cost $-2". Neither result is a real order.

Reflect. His question has an answer now: an empty field gives 0, not NaN. The page needs to decide which numbers it accepts, which is the subject of lesson 4.

At work

The second part of a README tells a stranger how to open the project and use it. Write it as numbered steps, and then follow your own steps on a computer that has never seen the project. A step that works only on your machine is a broken step.

Faisal wrote this for Salim:

How to open it

  1. On the repository page, click the green Code button, then Download ZIP.
  2. Unzip the file. You get a folder called muscat-dates-order-main.
  3. Double-click index.html in that folder. It opens in your browser.

How to use it

Type a number of boxes. The line under the field shows the total with delivery, and how many boxes the customer receives.

Each step is one action, with what the reader sees after it. "Open the project" would not be a step. It does not say which file, or how.

Your tasks

Task 1: Build the order page

Create the three files from the worked example. Type 5, then 10, and read the Console after each.

You are done when 10 boxes shows "Total for 10 boxes with delivery: $123. You receive 11 boxes." and the Console shows string number false.

Task 2: Predict, then look

Create values.html and values.js from "The idea". Before you open the page, add three lines of your own to values.js: "12" * 2, "12" + "2" and Number("12.5"), each inside console.log. Write down what you expect each to print.

You are done when the Console shows all nine lines and you can say why each of your three gave what it did.

Task 3: A price per kilo

Salim also sells loose dates at $9 a kilo. Add a second field for kilos and a second line that shows, for example, "3 kilos of loose dates: $27". Keep the prices in named const variables at the top of the file. Decide which variables in your function need let, if any.

You are done when both fields update their own lines while you type, and no let in your file could be a const.

Recap

  • A value is a number, a string or a boolean. typeof tells you which.
  • const makes a variable that keeps its value. let makes one you can change later.
  • A template literal, between backticks, puts values into text with ${...}.
  • The value of a field is always a string. Turn it into a number with Number() before arithmetic.
  • Number() gives NaN for text it cannot read, and 0 for an empty string. Number.isNaN() tells you whether a value is NaN.

Go deeper