Mr. Penney / ICS4U1 / JavaScript · Algorithms · HTML & CSS · React

JavaScript Reference

This sheet lists everything this course uses, in teaching order. Lesson markers say where each item is introduced.

Output and running code

console.log("text");        // print to the console
console.log(a, b);          // several values at once

Save the file, then click the ▷ Run button at the top right of the editor. What the file prints, and any error, appears in the OUTPUT panel at the bottom of the window.

Values and types — lesson 2

let count = 3;              // can be reassigned
const name = "Ada";         // cannot be reassigned
Type Example typeof
number 3, -2.5 "number"
string "text", `hi ${name}` "string"
boolean true, false "boolean"
undefined a declared but unassigned variable "undefined"
object { a: 1 }, [1, 2], null "object"

The two kinds of nothing

undefined is what JavaScript supplies when a value was never given: an unassigned variable, an omitted parameter, a function that ended without return, or a property an object does not have. null is what a programmer writes to record that there is deliberately no value. Return null from your own functions and leave undefined to the language.

let answer;                 // undefined
const grade = null;         // null
answer === grade            // false — two different values

Arithmetic, integer division and remainder

7 / 2            // 3.5   — JavaScript division is never integer division
Math.trunc(7/2)  // 3     — toward zero
Math.floor(7/2)  // 3     — toward negative infinity (differs for negatives)
7 % 2            // 1     — remainder
-7 % 2           // -1    — the sign follows the LEFT operand

Type conversion

Number("42")      // 42
Number("4a")      // NaN
String(42)        // "42"
Boolean("")       // false
"5" + 5           // "55"   — + JOINS when either side is text
"5" - 5           // 0      — - has no text meaning, so both convert
Number.isNaN(x)   // the only reliable NaN test

The limits of finite representation

0.1 + 0.2 === 0.3                          // false — binary cannot store 0.1 exactly
(0.1 + 0.2).toFixed(2) === (0.3).toFixed(2) // true — compare money to the nearest cent
Number.MAX_SAFE_INTEGER                    // 9007199254740991 — integers above this lose precision
(0.1 + 0.2).toFixed(2)                     // "0.30" — a STRING, not a number

Strings — lessons 1–5

A string is text. Its characters are numbered from zero, and every method below returns a NEW string rather than changing the original.

const name = "Ada Lovelace";
name.length              // 12
name[0]                  // "A"        — a single character, by position
name.toLowerCase()       // "ada lovelace"
name.toUpperCase()       // "ADA LOVELACE"
name.split(" ")          // ["Ada", "Lovelace"]   — an array, cut at each space
"  hi  ".trim()          // "hi"       — removes the spaces at both ends
"one\ntwo"               // prints on two lines: \n is a line break, one character long

Padding a string to a fixed width

Two methods pad a string out to a chosen length, and they pad opposite ends. Both leave a string that is already longer than the width alone.

"Name".padEnd(12)        // "Name        "  — pads the RIGHT, so text lines up in a column
"7".padStart(3, "0")     // "007"           — pads the LEFT, with a character you choose

The second argument is the character to pad with, and it defaults to a space.

Destructuring — lesson 2

Pull named parts out of an object, or the first values out of an array, in one line. The names on the left must match the object's keys.

const person = { name: "Ada", born: 1815 };
const { name, born } = person;          // two variables, in one line
const [first, second] = [10, 20];       // by position, from an array

function greet({ name }) { … }          // straight out of a parameter (lesson 14)

Comparison — lesson 2

a === b        // equal, no type conversion — always use this
a !== b
a < b          // on strings, compares character codes: "Z" < "a" is true

== converts types before comparing and is not used in this course.

Combining conditions — lesson 3

Until lesson 3, test one condition per if, with a separate if statement for each value:

if (a === null) {
  return null;
}
if (b === null) {
  return null;
}
a && b         // and — true when both are truthy
a || b         // or  — true when at least one is truthy
!a             // not — reverses the condition

Both && and || stop as soon as the answer is settled, so i >= 0 && values[i] > best never reads values[i] when i is negative. In Python these operators are the words and, or and not; JavaScript has no word forms.

Truthy and falsy

An if accepts any value. Exactly six values are falsy, and everything else is truthy:

false, 0, "", null, undefined, NaN   // the six falsy values
Boolean([])                          // true  — an empty array is TRUTHY
Boolean({})                          // true  — so is an empty object
Boolean("0")                         // true  — so is any string with a character in it

Test a collection with items.length > 0, not with items.

Control flow — lesson 3

if (score >= 80) { … } else if (score >= 50) { … } else { … }

for (let i = 0; i < 10; i++) { … }
for (const item of list) { … }          // each value
while (guess !== target) { … }

break;      // leave the loop now
continue;   // skip to the next pass

Functions — lesson 4

// The price after a discount.
// Precondition:  percent is from 0 to 100.
// Postcondition: returns price reduced by percent per cent.
function discounted(price, percent) {
  return price - (price * percent) / 100;
}

const double = (n) => n * 2;            // arrow function

[...arr].sort((a, b) => a - b);         // a sorted COPY, smallest first

The built-in sort with no comparator compares values as text, so [10, 9, 1].sort() gives [1, 10, 9]. It also sorts in place, which is why the example sorts a copy made with [...arr].

A function with no return gives back undefined.

Asking the user — lesson 5

const text = prompt("How many minutes? Type a whole number, such as 90.");  // a string, or null for Cancel
if (text === null) {
  // the user pressed Cancel: test for null before calling text.trim()
}
const minutes = Number(text);           // prompt() always returns text, so convert it first
alert(`${minutes} minutes is ${minutes / 60} hours.`);  // a message for the user to read

prompt() and alert() need a browser. Open your lesson's JavaScript file, then choose Terminal, Run Task, Preview My Page; the ▷ Run button says prompt is not defined. On the Lesson 5 calculator page, each question waits for an answer typed in the box under the conversation, and alert(), console.log() and any error appear in the conversation.

Arrays — lesson 6

const list = ["a", "b", "c"];
list[0]            // "a"          — first
list[list.length-1]// "c"          — last
list.length        // 3

list.push("d");            // add to the end
list.pop();                // remove and return the last
list.unshift("z");         // add to the front
list.shift();              // remove and return the first
list.slice(1, 3);          // a COPY of positions 1 and 2
list.splice(1, 1);         // removes 1 item at position 1, IN PLACE
[...list]                  // a copy
list.map((n) => n * 2);               // a new array, same length
list.filter((n) => n > 3);            // a new array, the ones that match

Objects — lesson 6

const person = { name: "Ada", born: 1815 };
person.name              // "Ada"
person["name"]           // same thing, when the key is in a variable
person.age = 36;         // add or change
Object.keys(person);     // ["name", "born", "age"] — an array of the object's own keys

const people = [ { name: "Ada" }, { name: "Alan" } ];   // array of objects
people.find((p) => p.name === "Alan");
JSON.stringify(person);  // object -> text
JSON.parse(text);        // text -> object

Classes — lesson 9

class Animal {
  #id;                              // private: unreachable from outside
  constructor(name, id) { this.name = name; this.#id = id; }
  speak() { return `${this.name} makes a sound`; }
  get id() { return this.#id; }     // read-only access
}

class Dog extends Animal {
  constructor(name, id) { super(name, id); }   // runs the parent's constructor first
  speak() { return `${this.name} barks`; }      // overrides the parent
}

const d = new Dog("Rex", 7);
d.speak();      // "Rex barks"
d.id;           // 7

Modules — lesson 10

This course writes its Node files in the CommonJS form: require brings a file in, and module.exports says what leaves it.

// maths.js
function add(a, b) { return a + b; }
class Calculator { … }
module.exports = { add, Calculator };   // the LAST line of the file; { add } is { add: add }

// main.js
const { add, Calculator } = require("./maths.js");   // the path starts with ./

Writing import or export in a file that also uses require or module.exports stops the file with an error, so each file uses one system throughout. The import form belongs to lesson 14, where React's build tool is what runs the code.

Files — lesson 10 (Node only, not the browser)

const { readFileSync, writeFileSync, existsSync } = require("node:fs");

existsSync("data.json");                 // true when the file is there, false when it is not
const text = readFileSync("data.json", "utf8");   // the file's text
const data = JSON.parse(text);           // JSON text back into an object
writeFileSync("data.json", JSON.stringify(data, null, 2));   // an object out as JSON text

Handling an error — lesson 10

Code that can fail while it runs — reading a file that is not there, parsing text that is not JSON — goes inside try. If it throws, the rest of the try is skipped and catch runs instead, so the program keeps going.

function readTheme(text) {
  try {
    const settings = JSON.parse(text);
    return settings.theme;
  } catch (error) {
    console.log("Could not read the settings:", error.message);
    return "light";                 // a value the caller can use
  }
}

Catch the error and return something the caller can act on. An empty catch hides the fault and is worse than no try at all.

Asynchronous code — lesson 16

async function showHours() {
  try {
    const response = await fetch("/hours.json");   // waits without freezing the page
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }
    const opening = await response.json();
    console.log(opening);
  } catch (error) {
    console.log(error.message);
  } finally {
    console.log("Finished asking.");
  }
}

showHours();

await is only legal inside an async function, and an async function always returns a promise. throw new Error(message) stops the function at that line; inside a try, it jumps to catch, where error.message is the message. finally runs after the try or the catch.

const branch = loadBranch() ?? "Riverside";   // the right side only when the left is null or undefined

Not taught in class — Level 4 material

Feature What it does
Map, Set collections with faster lookup than an array
Math.sqrt(16), 2 ** 3 the square root, 4; a power, 8
label?.trim() optional chaining: calls the method only when label is not null or undefined
parseInt("42px") reads digits until the first non-digit, giving 42. The course uses Number(), which rejects "42px"
text.slice(0, 3), text.includes("x") part of a string; whether a string contains another
list.indexOf(x), list.includes(x) the position of an item, or -1; whether an array contains an item
list.forEach(fn), list.reduce(fn, start) run a function on each item; combine every item into one value
a.localeCompare(b) dictionary order, returning a negative number, zero or a positive number
delete person.age removes a property from an object
x instanceof Animal whether an object was made by a class or one of its subclasses