Look up the JavaScript language and browser tools used in Sky Island Rescue. Each example comes from an actual course checkpoint.
Read one statement at a time. Start with the value it reads, then follow where its result goes. Some code examples are single lines that you can see in full in the linked lesson.
First instructions
Statements and semicolons
A statement gives JavaScript an instruction. A semicolon marks its end. This course shows the marks so each instruction is easy to spot.
console.log("Pip is at Central Hub.");
See it in use Lesson 1 · Lesson 2 · Lesson 3
Comments
Text after two slashes is a note. JavaScript skips it when the program runs.
// Sky Island Rescue: Pip checks in from Central Hub.
See it in use Lesson 1
Strings and quotes
Surround text with quotes to make a string. Quotes mark where the text begins and ends.
const rover = "Pip";
See it in use Lesson 2 · Lesson 4 · Lesson 9
Numbers and arithmetic
A number is a value you can calculate with. The usual arithmetic order applies, and parentheses let you group a calculation.
return energy - cost;
See it in use Lesson 8 · Lesson 9 · Lesson 10
Saving a value with const
Use const when the name should keep pointing at the same value. The contents of an array or object can still change.
const rover = "Pip";
See it in use Lesson 2 · Lesson 3 · Lesson 4
Updating a let variable
Use let for a value that will change, such as Pip’s location or energy.
let location = "Central Hub";
See it in use Lesson 2 · Lesson 7 · Lesson 12
Assignment and updates
One equals sign stores a value. Compound updates such as -= subtract from the existing value and store the result again.
pip.energy -= 2;
See it in use Lesson 9 · Lesson 10 · Lesson 16
Backticks and template literals
Backticks make a template string. JavaScript evaluates the expression in each dollar-sign-and-braces gap before displaying it.
const positionReport = `This is ${rover} at the ${location}.`;
See it in use Lesson 4 · Lesson 6 · Lesson 7
The console
The console is an output area. console.log displays a value so you can see an instruction’s result.
console.log("Pip is at Central Hub.");
See it in use Lesson 1 · Lesson 2 · Lesson 3
Strict equality
Three equals signs compare both value and type. An equals sign by itself has a different job: it stores a value.
const gateIsOpen = gate === "open";
Decisions, loops and functions
Booleans
The values true and false answer a yes-or-no question. They can store whether the rescue is complete.
const hasMap = true;
See it in use Lesson 5 · Lesson 10 · Lesson 18
if, else if and else
Run one path if its test passes. JavaScript tries any later else if tests in order, then uses else when none passes.
} else if (!enoughEnergy) {
See it in use Lesson 5
Logical AND and OR
Use && when both checks must pass. Use || when either is enough, or to provide a fallback for a falsy value.
const ready = enoughEnergy && gateIsOpen && hasMap;
See it in use Lesson 5 · Lesson 10 · Lesson 17
Logical NOT and not equal
An exclamation mark reverses the test. The !== operator checks whether the values differ without type conversion.
if (stop.part !== "" && !robot.toolkit.includes(stop.part)) {
See it in use Lesson 10 · Lesson 16 · Lesson 17
Conditional expressions
Use condition ? first : second to choose one value. The question mark introduces the true choice and the colon introduces the other one.
showMessage("No energy left. " + (state.place === "Sky Dock" ? "Recharge to travel." : "Reload the page to try again."));
See it in use Lesson 16 · Lesson 17 · Lesson 18
for...of
Read the values in a sequence one at a time. The local name is each item in turn.
for (const stop of stops) {
See it in use Lesson 7 · Lesson 10 · Lesson 13
Counting loops
A counting loop has a start, a check and an update. JavaScript checks first each time, runs the body, then updates the counter.
for (let index = 0; index < costs.length; index += 1) {
See it in use Lesson 7 · Lesson 31 · Lesson 32
Queues and a growing search
A queue lets a search remember what to visit next. A counting loop can keep checking new entries as the queue grows.
for (let head = 0; head < queue.length; head += 1) {
See it in use Lesson 35 · Lesson 36 · Lesson 37
Functions, parameters and arguments
A function is a named set of instructions. Parameters name incoming values. Arguments are the values you pass when calling it.
function travel(energy, cost) {
See it in use Lesson 8 · Lesson 10 · Lesson 13
return and guard clauses
Return hands a value back to the caller and leaves the function. An early return can stop an invalid move before it spends energy.
return energy;
See it in use Lesson 8 · Lesson 10 · Lesson 14
Arrow functions
The => arrow makes a function, often a short callback passed to an array method or event listener.
const ready = needed.every(part => state.inventory.includes(part));
See it in use Lesson 18 · Lesson 19 · Lesson 20
Switch and case
A switch checks one value against several labels. A return or break can end a branch so it does not carry on into the next one.
switch (action.type) {
Collections and copies
Arrays and indexes
Square brackets make an ordered list. The first position is zero. The length tells you how many positions there are.
const toolkit = ["torch", "spanner"];
See it in use Lesson 6 · Lesson 7 · Lesson 10
Objects and properties
Braces can make an object whose entries have names. A colon joins a property name to its value.
const pip = {
See it in use Lesson 9 · Lesson 10 · Lesson 15
Dot notation and bracket lookup
A dot accesses a property with a fixed name. Put a variable in brackets when the program must work out which property to read.
if (!routes[state.place].includes(destination)) {
See it in use Lesson 15 · Lesson 16 · Lesson 17
Spread syntax
Three dots copy or unpack the entries of an array or object. This is a shallow copy. Any nested objects remain shared unless copied too.
const moveButtons = [...document.querySelectorAll("[data-destination]")];
See it in use Lesson 15 · Lesson 16 · Lesson 17
Destructuring and shorthand
Destructuring gives names to entries taken from an array or object. In a new object, shorthand lets a property use a variable with the same name.
const { room, energy } = state;
See it in use Lesson 22 · Lesson 23 · Lesson 24
Array push and includes
push adds an item to an array. includes checks whether an item is present, so Pip can avoid picking up the same part twice.
if (!toolkit.includes(discovery)) {
See it in use Lesson 6 · Lesson 9 · Lesson 10
map, filter and find
Use map to transform each item, filter to keep matching items, and find to get just the first match.
const missing = targets.filter((target) => !state.bag.includes(target.id));
See it in use Lesson 24 · Lesson 45 · Lesson 50
every, some and reduce
every checks all items. some checks for any match. reduce combines values into one running result, such as the final state in a replay.
const ready = needed.every(part => state.inventory.includes(part));
See it in use Lesson 18 · Lesson 19 · Lesson 20
join, slice and at
join combines list items into text. slice copies part of a list. at can read from the end when its position is negative.
document.querySelector("#inventory").textContent = state.inventory.join(", ") || "Empty";
See it in use Lesson 17 · Lesson 18 · Lesson 19
Maps and Sets
A Map matches keys to values. A Set remembers unique values. Both help the game look things up without walking a whole array first.
new Set(state.bag).size !== state.bag.length ||
See it in use Lesson 27 · Lesson 28 · Lesson 30
Null, undefined and fallbacks
null means a value is deliberately absent. undefined often means a property is missing or a function returned nothing. The ?? operator uses a fallback for either.
line.push(hasPip ? "P" : (landmarks[label] ?? "."));
See it in use Lesson 31 · Lesson 32 · Lesson 33
Optional chaining
The ?. check stops access and gives undefined if the receiver is missing. It lets a save checker inspect a value safely.
if (data?.version !== 1 ||
See it in use Lesson 44 · Lesson 46 · Lesson 50
Object.freeze
Freeze prevents direct changes to an object’s own properties. It does not automatically freeze nested objects.
const Game = Object.freeze({ makeState, move, collect, repair });
Web pages and controls
HTML elements and ids
HTML gives a page its structure. An id identifies one element so JavaScript can find it. The JavaScript variable that holds it can have another name.
const report = document.querySelector("#report");
See it in use Lesson 11 · Lesson 12 · Lesson 13
querySelector and querySelectorAll
The first returns one matching element or null. The second returns a collection of all matches.
const buttons = document.querySelectorAll("[data-destination]");
See it in use Lesson 13 · Lesson 15 · Lesson 16
textContent
Set textContent to change what an element says. The browser displays the value as text.
report.textContent = "Pip has reached " + destination + ".";
See it in use Lesson 11 · Lesson 12 · Lesson 13
Input values and forms
Use value for text typed in a field. A number input’s valueAsNumber reads a number or NaN when no valid number was entered.
const callSign = input.value.trim();
See it in use Lesson 14 · Lesson 49 · Lesson 50
Event listeners and callbacks
An event listener gives the browser a function to call later, such as when a player clicks a button or submits a form.
button.addEventListener("click", scan);
See it in use Lesson 12 · Lesson 13 · Lesson 14
Event objects and keys
The browser passes the event object to a handler. Its key property tells you which key was pressed.
const index = keys.indexOf(event.key);
See it in use Lesson 19 · Lesson 20 · Lesson 32
Target, currentTarget and dataset
target is where the event began. currentTarget is the element with the listener. dataset reads the element’s data attributes.
const destination = event.currentTarget.dataset.destination;
See it in use Lesson 13 · Lesson 15 · Lesson 16
Preventing the default action
preventDefault asks the browser to skip its usual response, for example submitting the form by navigating away.
event.preventDefault();
See it in use Lesson 14 · Lesson 32 · Lesson 33
Disabled controls, focus and status
Disable controls that cannot be used. Use focus to move keyboard attention and a live status to announce meaningful game changes.
button.disabled = scanIndex === scans.length - 1;
See it in use Lesson 12 · Lesson 14 · Lesson 18
Render and state
State describes the mission now. Rendering reads that state and displays it. Keeping them separate lets you check rules without opening the page.
function render() {
See it in use Lesson 12 · Lesson 15 · Lesson 16
Animation frames and timestamps
requestAnimationFrame schedules the next visual update before a repaint. The timestamp lets the game measure elapsed time.
if (!state.lit) requestAnimationFrame(tick);
See it in use Lesson 37 · Lesson 38 · Lesson 39
Cancelling an animation frame
Cancel a pending frame by giving the browser its request number. Keep the state check too so a paused game does not move.
cancelAnimationFrame(frame);
Files, time and tests
JSON.stringify and JSON.parse
Stringify turns supported values into JSON text. Parse reads valid text back. Check the shape and types before trusting a save.
return JSON.stringify({ version: 1, state });
See it in use Lesson 27 · Lesson 28 · Lesson 29
Validation and type checks
Validate data before it changes the game. Use Number.isInteger, Array.isArray and typeof to check the kinds of values you received.
!Number.isInteger(state.energy) ||
See it in use Lesson 27 · Lesson 28 · Lesson 29
Local storage
localStorage keeps strings for this site in the current browser. Save JSON text and handle unavailable storage gracefully.
return decodeSave(localStorage.getItem(slot));
See it in use Lesson 44 · Lesson 46 · Lesson 50
try, catch and throw
Code in try can throw a problem. A nearby matching catch can handle it and leave the game playable.
try {
See it in use Lesson 26 · Lesson 27 · Lesson 28
finally
A finally block runs when leaving the try/catch sequence, whether the work succeeds or fails.
} finally {
See it in use Lesson 48 · Lesson 50
Remainders and seeded sequences
The % operator gives the remainder. A game seed helps generate the same mission again when you start with the same seed and rules.
const supplies = (seed * 17 + 11) % 3;
See it in use Lesson 29 · Lesson 30
Bit flags and unsigned shifts
A number can hold several yes-or-no flags in its binary digits. A shift can move those digits. The >>> shift fills the left side with zeros.
const parts = state.parts | (mission.pickup[room] ?? 0);
See it in use Lesson 41 · Lesson 42 · Lesson 43
Pure rules and values returned
A pure game rule calculates a result from its inputs without editing the page or changing those inputs. A replay can run the same rules again.
function move(state, destination) {
See it in use Lesson 21 · Lesson 22 · Lesson 23
Shortest routes
Breadth-first search checks places one step away before checking places two steps away. A queue controls the order, and a Set tracks visits.
function findRoute(start, goal) {
See it in use Lesson 35 · Lesson 36 · Lesson 37
Replaying actions
Replay starts from the same state and feeds the saved commands to the same rules. Matching inputs should produce the same result.
function replay(seed, actions) {
See it in use Lesson 29 · Lesson 30 · Lesson 44
Assertions and regression tests
An assertion compares an outcome with what you expect. Rerun past tests after a change to check that old behaviour still works.
function check(condition, label) {
See it in use Lesson 30 · Lesson 40 · Lesson 46
Promises and resolve
A promise represents an outcome arriving later. Calling resolve gives it its successful result.
return new Promise(resolve => {
See it in use Lesson 48 · Lesson 50
async and await
An async function returns a promise. await pauses that function for the result, while the browser can continue other work.
const message = await getBriefing(requestedMission);
See it in use Lesson 48 · Lesson 50
setTimeout
Schedule a function to run after a delay measured in milliseconds. The delay is a minimum wait, since the browser may still be busy.
setTimeout(() => {
See it in use Lesson 48 · Lesson 50
An interface for game rules
An interface is the small set of functions another part of the program uses. It lets the controls and display share the same game engine.
const Game = Object.freeze({ makeState, move, collect, repair });
Explore more JavaScript
These experiments use Pip’s world to show features you can use in other games and projects. Run each example in a fresh JavaScript editor, then change one value and see what happens.
Names, functions and decisions
Block scope and older var declarations
Braces mark a block. A name declared with let or const inside a block stays inside that block. Older var declarations stay visible across blocks inside the same function. Read the lines from top to bottom to see where each name can be used.
function openDock() {
if (true) {
let signal = "green";
var gate = "open";
console.log(signal);
}
console.log(gate);
}
openDock();
Check your output
green
openTypes and explicit conversion
A reading can arrive as text, such as an input value. Number converts suitable text into a number. Use typeof to check the resulting type. If the text cannot be converted, Number returns the special number value NaN.
const reading = "6";
const energy = Number(reading);
console.log(typeof reading, typeof energy, energy + 1);
console.log(Number.isNaN(Number("storm")));
Check your output
string number 7
trueDefault and rest parameters
A default is the value a function uses when its argument is missing or undefined. A rest parameter starts with three dots and gathers the remaining arguments into one array. Here the radio channel has a default and the messages can be as long a list as you need.
function report(channel = "Dock", ...messages) {
return `${channel} heard ${messages.length} messages`;
}
console.log(report());
console.log(report("Garden", "Hello", "Safe"));
Check your output
Dock heard 0 messages
Garden heard 2 messagesClosures
A function keeps access to the names in the place where it was created. Each call to makeCounter creates its own local total. The returned function can still update that total after makeCounter has finished.
function makeCounter() {
let total = 0;
return () => { total += 1; return total; };
}
const countRescues = makeCounter();
console.log(countRescues());
console.log(countRescues());
Check your output
1
2while, do...while, break and continue
A while loop checks before it starts each turn. A do…while loop checks after each turn, so it always runs once. Continue skips the rest of the current turn. Break leaves the loop right away.
let scans = 0;
do { scans += 1; } while (false);
while (scans < 5) {
scans += 1;
if (scans === 2) continue;
if (scans === 4) break;
console.log(scans);
}
console.log(`Stopped at ${scans}`);
Check your output
3
Stopped at 4Regular expressions
A regular expression describes a text pattern. Here ^ marks the start, [A-Z] matches one capital letter, {2} asks for two of them, and $ marks the end. Test tells you whether the whole call sign fits.
const callSignPattern = /^[A-Z]{2}$/;
console.log(callSignPattern.test("PI"));
console.log(callSignPattern.test("Pip"));
Check your output
true
falseObjects and special kinds of data
Classes, new and this
A class defines how to build an object and which actions it can take. New creates a rover and calls its constructor. Inside the method, this refers to the rover receiving the call.
class Rover {
constructor(name) { this.name = name; }
call() { return `${this.name} here!`; }
}
const pip = new Rover("Pip");
console.log(pip.call());
Check your output
Pip here!Inheritance and prototypes
Extends lets a class reuse behaviour from another class. JavaScript finds a method by looking along the object's prototype chain, which links it to objects that supply shared behaviour. The rescue rover can use the call method even though it was defined on Rover.
class Rover {
call() { return "Reporting in"; }
}
class RescueRover extends Rover {
help() { return `${this.call()} for rescue`; }
}
console.log(new RescueRover().help());
Check your output
Reporting in for rescuePrivate fields and getters
A private field starts with # and can be accessed only from within its declaring class. A getter runs when you read its property. The game can read the charge label while the class controls how the energy is stored.
class Battery {
#energy = 6;
get label() { return `${this.#energy} cells left`; }
}
const battery = new Battery();
console.log(battery.label);
Check your output
6 cells leftBigInt
BigInt stores whole numbers of any size that memory allows. Put n after a whole number literal to create one. Use the same type on both sides of ordinary arithmetic with BigInt.
const stars = 9007199254740993n;
console.log(String(stars + 1n));
Check your output
9007199254740994Symbols and computed keys
Each call to Symbol here makes a distinct value, even when the descriptions match. Use square brackets around a symbol to turn it into a property key. Each sensor can keep its own reading without replacing the other one.
const nose = Symbol("sensor");
const tail = Symbol("sensor");
const readings = { [nose]: 4, [tail]: 7 };
console.log(readings[nose], readings[tail]);
Check your output
4 7Typed arrays
Typed arrays hold numeric values with a specific storage format. Uint8Array stores unsigned integers from 0 to 255. A small tile map can use 0 for open sky and 1 for a landing pad.
const tiles = new Uint8Array(3);
tiles[1] = 1;
console.log(tiles.join(", "));
Check your output
0, 1, 0Modules, sequences and work that finishes later
Iterators and generators
An iterator supplies one item at a time. A generator is a function with a star. Each yield pauses it and provides one item. A for…of loop asks for the next item until the generator is done.
function* patrol() {
yield "Dock";
yield "Beacon";
}
for (const place of patrol()) console.log(place);
Check your output
Dock
BeaconES modules, export and import
Export makes a name available to other files. Import asks for that name. Save the first two lines shown as battery.mjs and the last three as mission.mjs in the same folder. Run the mission file in a JavaScript environment that supports ES modules, or load it as a module from a page served by your editor.
// battery.mjs
export const fullEnergy = 6;
// mission.mjs
import { fullEnergy } from "./battery.mjs";
console.log(`Ready at ${fullEnergy}`);
Check your output
Ready at 6Combining promises
Promise.all waits for every listed promise to succeed and gives you their values in the same order as the input. If any promise rejects, the combined promise rejects too. Use it when the mission needs both readings before it can begin.
async function prepare() {
const readings = await Promise.all([
Promise.resolve("Wind ready"),
Promise.resolve("Radio ready")
]);
console.log(readings.join(". "));
}
prepare();
Check your output
Wind ready. Radio readyThrowing useful errors
Throw passes a problem up to the caller. An Error object stores a message. A catch block reads it and explains what happened so the player can correct the input.
function checkBattery(cells) {
if (cells < 1) throw new RangeError("Battery is empty");
return cells;
}
try { checkBattery(0); }
catch (problem) { console.log(problem.message); }
Check your output
Battery is emptyFor a wider lookup, use the MDN JavaScript Guide or the MDN JavaScript Reference.