Mr. Penney / TAS1O1 / HTML · CSS · JS · Canvas · Gemini

JavaScript Reference

Everything this course teaches in JavaScript, in the order you meet it, followed by the material that Level 4 tasks expect you to find for yourself. Drawing and games are on the Canvas and Game Reference Sheet, which covers Lessons 19 to 24.

Lesson 14 and Lessons 17 to 24 are extension lessons: they are not taught in class, but their sections stay on this sheet for anyone who wants to use input boxes, loops, arrays or objects in the Final Project.

How to use this sheet

There are two ways in. If you are part-way through a level and need to remember how something is written, read the section for that lesson under Taught in class. Those sections are in the order the course teaches them, so nothing below your current lesson is needed yet.

If you are attempting a Level 4 task, find your lesson in the table below. It names the one section to read, and it says so plainly when a task needs nothing new at all.

What each Level 4 task needs

Lesson What its Level 4 asks for What to read
0 A label printed beside a value, and a quotation mark inside a message A label beside a value, then Quotation marks inside a message
10 Swapping two variables, and splitting minutes into whole hours and the minutes left over Whole groups and what is left over
11 A leapYear variable decided by a rule with two exceptions Combining two conditions, and the remainder in Whole groups and what is left over
12 partyInvite(name, day) returns an invitation that is stored and printed Read Lesson 12 below and combine parameters with a return.
13 The picture changes when the counter reaches 10 Nothing new. Read Lesson 11 and Lesson 13 above and use them together.
14 A number box that might not hold a number Checking what the user typed
15–16 A timer that changes the page by itself Major Project 2 — a timer below, and setInterval — a countdown in the Level 4 section.
17 fizzy(n), where the order of your ifs is the puzzle The level sheet gives you every line you need. % and && are explained in Combining two conditions.
18 spawnEnemies(n), returning a list of new objects Nothing new. Read Lesson 18 above: a loop, push, and an object literal.
19–24 Drawing, movement, controls and collision The Canvas and Game Reference Sheet

Taught in class

Lesson 0 — printing, comments and arithmetic

console.log("Hello");        // a message: the quotation marks say where it starts and ends
console.log(12 * 3);         // a calculation, worked out before it prints — 36
console.log("12 * 3");       // in quotation marks it is text, printed exactly as written

// A line starting with // is a comment. It is a note for a person, and the computer skips it.

//  +  add     -  subtract     *  multiply     /  divide

Lesson 10 — variables and strings

A variable is a labelled box that stores one value.

const topic = "sourdough";   // const is locked once it has been filled
let score = 0;               // let can be refilled later
score = score + 1;

console.log(score);          // no quotation marks means the value in the box
console.log("score");        // quotation marks means the word itself

const name = "Ada";
const line = `Hello ${name}, you have ${score} points`;   // a template literal uses backticks

helper.js also copies anything you print into the #output box on your page, so from Lesson 10 onwards you can read the output without opening the browser's own console.

Lesson 11 — if and else

const age = 15;
let ticketPrice = 0;

if (age >= 18) {
  ticketPrice = 12;
} else if (age >= 13) {
  ticketPrice = 8;
} else {
  ticketPrice = 5;
}

console.log(ticketPrice);

The comparisons are == equal to, != not equal to, < less than, > greater than, <= less than or equal to, and >= greater than or equal to. One equals sign stores a value in a variable; two equals signs compare two values.

if (answer == "Ottawa") {
  feedback = "Correct.";
} else {
  feedback = "Try again.";
}

From Lesson 12 the examples write === and !==. They test the same thing as == and !=, and also require both values to be the same type, so 8 == "8" is true but 8 === "8" is false.

Use >= or <= when the boundary value is included. Do not combine > or < with a separate equality test.

Lesson 12 — functions

A function is a named set of steps. Declaring it defines the steps; calling it runs them. Parentheses hold its parameters, and braces hold its steps.

A function with no parameters or return prints inside its braces. The empty parentheses mean there are no inputs.

function showReminder() {
  console.log("Save your work.");
}

showReminder();
showReminder();

A function with a parameter receives a value from each call. The parameter is a variable named in the declaration's parentheses. This example still prints inside the function and has no return.

function showReminder(task) {
  console.log(task);
}

showReminder("Save your work.");
showReminder("Refresh the browser.");

A function with a return sends a value back to the call. Store the returned value in a variable, then print the variable. This example takes no parameters.

function weeklyMinutes() {
  return 5 * 60;
}

const minutes = weeklyMinutes();
console.log(minutes);

return does not print anything. If a function prints inside its braces without returning a value, assigning its call to a variable stores undefined. Add return when the caller needs the result.

Combining parameters and a return is Lesson 12's Level 4 skill. The input affects the returned result, which is stored and printed outside the function.

function practiceMinutes(sessions) {
  return sessions * 20;
}

const total = practiceMinutes(4);
console.log(total);

A function with two parameters writes a comma between their names. Its call supplies two values in the same order.

Lesson 13 — buttons and events

Every interactive page does the same three things in order: it finds an element, it listens for something to happen, and it changes the page in response.

// A click replaces the words in #status.
const magicButton = document.getElementById("magic-button");
magicButton.addEventListener("click", function () {
  document.getElementById("status").textContent = "The button was clicked.";
});

// A counter. count is declared outside the click, so it keeps its value between clicks.
let count = 0;
const countButton = document.getElementById("count-button");
countButton.addEventListener("click", function () {
  count = count + 1;
  document.getElementById("count").textContent = count;
});

// A click changes the picture that <img id="photo"> shows.
const imageButton = document.getElementById("image-button");
imageButton.addEventListener("click", function () {
  document.getElementById("photo").src = "images/flower.svg";
});

Major Project 2 — a timer

setInterval runs a function again and again, with a wait between each run. It takes two things: the function to run, and how many milliseconds to wait. There are 1000 milliseconds in one second. Start the timer once, at the bottom of script.js, outside every click.

let score = 0;

setInterval(function () {
  score = score + 1;
  document.getElementById("score").textContent = score;
}, 1000);   // runs once every second

Lesson 14 — input boxes

An input box always hands you text, even when the student typed a number, so convert it before you calculate with it.

const typed = document.getElementById("user-input").value;   // always text
const asNumber = Number(typed);                              // now it is a number

Lesson 17 — loops

A loop repeats a step many times without repeating the line.

for (let i = 1; i <= 10; i = i + 1) {
  console.log(i);
}

Lesson 18 — arrays, objects and randomness

An array is one variable holding many values. An object is data with named parts.

const favs = ["pizza", "shawarma", "pho"];
favs[0];        // "pizza" — counting starts at 0
favs.length;    // 3
favs.push("banh mi");

const hero = { name: "Rex", hp: 100, move: "bite" };
hero.name;      // "Rex"
hero.hp = 90;

Math.random();      // a random decimal from 0 up to, but not including, 1
Math.floor(4.9);    // 4 — it chops the decimal off and never rounds up

Math.floor(Math.random() * 6) + 1;              // a die: 1, 2, 3, 4, 5 or 6
list[Math.floor(Math.random() * list.length)];  // one random item out of a list

A whole working page

The sections above are one idea each. Here they are together, as three files that talk to each other. This is the shape of every interactive thing you build from Lesson 13 onwards.

<!-- index.html -->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Snack Counter</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Snack Counter</h1>
    <input id="snack-input" type="text" placeholder="A snack">
    <button id="add-button">Add</button>
    <p id="summary-line"></p>
    <ul id="snack-list"></ul>
    <script src="helper.js"></script>
    <script src="script.js"></script>
  </body>
</html>
// script.js
const snacks = [];

// Plain functions, outside the browser block, so the checker can test them.
function addSnack(list, name) {
  if (name.trim() === "") {
    return list;
  }
  list.push(name.trim());
  return list;
}

function summary(list) {
  return `You have ${list.length} snacks.`;
}

// Everything that touches the page goes inside this block, so loading the file
// outside a browser never crashes.
if (typeof document !== "undefined") {
  const input = document.getElementById("snack-input");
  const list = document.getElementById("snack-list");

  document.getElementById("add-button").addEventListener("click", function () {
    addSnack(snacks, input.value);
    input.value = "";
    document.getElementById("summary-line").textContent = summary(snacks);

    list.innerHTML = "";
    for (let i = 0; i < snacks.length; i = i + 1) {
      const row = document.createElement("li");
      row.textContent = snacks[i];
      list.appendChild(row);
    }
  });
}

addSnack and summary sit outside the browser block, which is why the checker can test them. All the document wiring sits inside it. The five lines that rebuild the <ul> are explained below, under Turning an array into a list on the page.

Not taught in class — Level 4 material

Level 4 tasks expect you to find what you need here and work out how to use it. The sections are in the order the course needs them, and the table at the top of this sheet says which one is yours.

A label beside a value — Lesson 0

console.log prints one thing. Give it two, separated by a comma, and both print on the same line, which is how a number gets a word beside it saying what it is.

console.log("Minutes in a week:", 7 * 24 * 60);   // Minutes in a week: 10080

Quotation marks inside a message — Lesson 0

A message starts and ends with a quotation mark, so a quotation mark in the middle of one ends it early and the rest of the line becomes an error. There are three ways to print one anyway, and all three print the same line.

console.log("She said \"hello\" and left.");  // a backslash marks it as part of the message
console.log('She said "hello" and left.');    // single quotes start and end the message instead
console.log(`She said "hello" and left.`);    // backticks do the same job

The backslash is called an escape. It works the other way round too, so 'It\'s fine.' prints It's fine.

Whole groups and what is left over — Lessons 10, 11 and 17

Two tools answer "how many whole groups, and what is left over": one for the groups, one for the remainder.

Math.floor(4.9);   // 4 — chops the decimal off, and never rounds up
Math.round(4.5);   // 5 — normal rounding
17 % 5;            // 2 — the remainder after dividing, said as "mod"

Use them together for hours from minutes, dollars from cents, or rows from items.

const totalMinutes = 137;
const hours = Math.floor(totalMinutes / 60);   // 2
const minutesLeft = totalMinutes % 60;         // 17

% is also how you ask whether one number divides another exactly, which is what Lesson 11's leap years and Lesson 17's FizzBuzz both need. A remainder of 0 means it divides exactly.

if (i % 3 === 0) { ... }   // true when i is a multiple of 3

Math.floor is taught in class on Lesson 18. Before Lesson 18 it is a Level 4 tool, and after it is an ordinary one, which is why it appears in both halves of this sheet.

Combining two conditions — Lessons 11 and 17

if (year % 4 == 0 && year % 100 != 0) { ... }   // && means both must be true
if (day == "sat" || day == "sun") { ... }       // || means either one is enough

When several conditions could match the same value, test the most specific one first. A number that is a multiple of both 3 and 5 also passes the test for 3 on its own, so the combined test has to come before either single one.

Checking what the user typed — Lesson 14

An input box hands you whatever was typed, including nothing at all and including words. Two tools handle that.

"  Ada  ".trim();   // "Ada" — removes spaces from the start and end, nothing in the middle
"   ".trim();       // ""    — a box holding only spaces is empty once trimmed

.trim() gives you the real text out of an input box, so a student who typed three spaces counts as having typed nothing.

Number.isNaN(Number("abc"));   // true  — "abc" is not a number
Number.isNaN(Number("7"));     // false — "7" is a number

Number("abc") produces NaN, which stands for "not a number", and Number.isNaN(...) is the test for it. You cannot test for NaN with ===, because NaN === NaN is false. NaN is the only value in JavaScript that is not equal to itself, which is why a built-in function exists to do the test.

const typed = document.getElementById("age-input").value;

if (typed.trim() === "") {
  return "Type a number first.";
}
if (Number.isNaN(Number(typed))) {
  return "That is not a number.";
}
return Number(typed) * 2;

String methods

"quiet".toUpperCase();   // "QUIET"
"LOUD".toLowerCase();    // "loud"
"pizza".length;          // 5
"hello".includes("ell"); // true

setInterval — a countdown

Major Project 2 Level 4 teaches setInterval, and the section Major Project 2 — a timer above shows it. This is a second example: a countdown that a function works out. Canvas games do not use setInterval; they use requestAnimationFrame, which is on the Canvas and Game Reference Sheet.

// A function that works out the next number in the countdown.
function countdown(seconds) {
  if (seconds <= 0) {
    return 0;
  }
  return seconds - 1;
}

let timeLeft = 15;

// The timer runs the function inside it once every second.
setInterval(function () {
  timeLeft = countdown(timeLeft);
  document.getElementById("timer-display").textContent = `Time left: ${timeLeft}`;
}, 1000);   // runs every 1000 milliseconds, which is every second

Turning an array into a list on the page

The array is the data, and the <ul> is a picture of it. To show the current array, empty the <ul> and rebuild it, one <li> per item.

const list = document.getElementById("snack-list");
list.innerHTML = "";                                  // remove every old <li> first
for (let i = 0; i < snacks.length; i = i + 1) {
  const row = document.createElement("li");           // make a new <li>, not yet on the page
  row.textContent = snacks[i];                        // put the item's text in it
  list.appendChild(row);                              // add it to the end of the <ul>
}

Run all of it every time the array changes. Without the innerHTML = "" line the old rows stay and the list doubles on every click.

More array, timer, and page methods

Code What it does
list.includes(x) true if the array contains x
list.splice(i, 1) Removes the item at position i from the array
setTimeout(fn, ms) Runs a function once, after a delay of ms milliseconds
element.remove() Deletes an element from the page
btn.disabled = true; Greys out a button so clicks do nothing; btn.disabled = false; turns it back on
JSON.stringify(obj) Turns an object into printable text, which is useful for debugging