Introduction
Getting Started · TypeScript/JavaScript 1
JavaScript and TypeScript
JavaScript is the language of the web browser, and with Node.js it runs on your computer too. It is interpreted and dynamically typed. TypeScript is JavaScript plus types: you write .ts files with type annotations, the TypeScript compiler (tsc) checks them and produces ordinary .js files that run anywhere JavaScript runs. Every JavaScript program is already a TypeScript program; the types are extra safety the compiler checks for you.
- Node.js from nodejs.org, which brings
node(runs JavaScript) andnpm(installs packages). Check withnode --version. - TypeScript:
npm install -g typescriptgives youtsc. Or run a.tsfile directly withnpx tsx hello.ts. - An editor: VS Code is written in TypeScript and understands it out of the box, underlining type errors as you type.
- Transpile — what
tscdoes: it translates TypeScript into JavaScript and strips the types - Type annotation —
: numberafter a name, telling the compiler what it holds - Runtime — where the JavaScript actually runs: a browser or Node
Your First Program
hello.ts
// My first program
console.log("Hello, World!");Run it from a terminal
npx tsc hello.ts # produces hello.js
node hello.js
# or, in one step while learning:
npx tsx hello.tsHello, World!Read it
- Lines starting with
//are comments;/* ... */spans several lines. console.log(...)prints its arguments separated by spaces, then a newline.- The text in quotes is a string. Single or double quotes both work; backticks make a template literal that can hold
${...}. - Semicolons are optional in JavaScript but almost every style guide uses them; this sheet does.
More console.log
console.log("Hello", "World"); // Hello World
console.log("The answer is", 6 * 7); // The answer is 42
console.log(`The answer is ${6 * 7}`); // template literal: any expression inside ${ }
console.error("Something went wrong"); // to the error streamVariables, Blocks and Style
let count = 0; // let: a variable that will change
const MAX_SIZE = 100; // const: cannot be reassigned (use it by default)
let name: string = "Harry"; // TypeScript: an explicit type annotation
let total = 0; // the compiler INFERS number from the value; annotate only when it cannot
if (count > MAX_SIZE) {
console.log("Too many"); // braces group statements; indent the inside
}Conventions
- Variables and functions in lowerCamelCase:
totalScore,printBalance() - Classes, interfaces and types in UpperCamelCase:
BankAccount - Constants in ALL_CAPS when they are true constants:
MAX_SIZE - Prefer
const; useletonly when the variable must change; never usevar(its scoping rules are the source of classic bugs). - Four spaces or two, consistently; semicolons; lines under about 100 characters. A formatter such as Prettier settles it for you.
Comments
// One line, to the end of the line
/* Several lines,
between the markers */
/**
* A JSDoc comment above a function. Editors show it when you hover.
* @param sideLength the length of one side
* @returns the volume
*/Three Kinds of Errors
| Kind | When it shows up | Example |
|---|---|---|
| Compile-time (type) error | When tsc runs, or as a red underline in the editor; the .js is still produced unless you tell tsc otherwise | Passing a string where a number is expected, calling a method that does not exist, a misspelled variable |
| Run-time error (exception) | While running; Node prints a stack trace and stops | TypeError: Cannot read properties of undefined, RangeError, JSON.parse on bad text |
| Logic error | Never announced; the program runs and gives the wrong answer | == where === was meant, sorting numbers with the default sort(), an off-by-one |
What the messages look like
tsc, when average.ts passes a string to a number parameter
average.ts(4,12): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.node, when a method is called on a variable that holds nothing
average.js:2
c.deposit(1);
^
TypeError: Cannot read properties of undefined (reading 'deposit')
at file:///home/ann/average.js:2:3- 1. A
tscmessage isfile(line,column): error TScode:and a sentence. The sentence names both types; the one it says is “not assignable” is what you passed, the other is what was expected. TheTSnumber is searchable. - 2. A Node message starts with the file and line, shows the line with a caret, then the error name and message, then
atlines. The firstatline is where it happened; the ones below are the calls that led there. - 3.
Cannot read properties of undefined (reading 'x')means the thing before.xwasundefined: a misspelled variable, an array position past the end, aMap.getthat found nothing, or a lostthis.
In plain JavaScript: there is no compile step and no type checking. Everything on this sheet works in JavaScript if you delete the type annotations (: number, : string, interface, <T>). The run-time and logic errors are exactly the same in both.
Programming with Numbers and Strings
Getting Started · TypeScript/JavaScript 1
Variables and Types
JavaScript has one number type, number, which is a 64-bit float: there is no separate integer type, and no integer division. TypeScript lets you name the type of a variable; most of the time it infers it from the first value and you write nothing.
let cansPerPack = 6; // number (inferred)
let canVolume = 0.335; // number
let done = false; // boolean
let name = "Harry"; // string
const MAX_SIZE = 100;
let nothing: number | undefined; // declared, not yet assigned: undefined
let big = 9007199254740993n; // bigint, for whole numbers beyond 2^53
console.log(typeof canVolume); // "number"
cansPerPack = "six"; // TypeScript error: string is not assignable to number| Type | Holds | Notes |
|---|---|---|
number | All numbers, whole or decimal | Exact for whole numbers up to 253; 0.1 + 0.2 === 0.3 is false |
string | Text | Immutable: methods return new strings |
boolean | true or false | The result of every comparison |
undefined | “never given a value” | A declared-but-unassigned variable, a missing property, a function with no return |
null | “deliberately no value” | You assign it on purpose. typeof null is "object", a famous wart |
bigint | Arbitrarily large whole numbers | Literal ends in n; cannot mix with number without converting |
any | Anything, unchecked | Turns TypeScript off for that variable. Avoid it; unknown is the safe version |
Arithmetic
| Operator | Meaning | Example |
|---|---|---|
+ - * | Add, subtract, multiply | 7 * 3 → 21 |
/ | Division, always decimal | 7 / 2 → 3.5; for the whole part use Math.floor(7 / 2) → 3 or Math.trunc |
% | Remainder | 7 % 2 → 1; n % 2 === 0 tests for even |
** | Power | 2 ** 10 → 1024 |
++ -- | Add or subtract 1 | count++; |
+= -= *= /= | Combine and assign | total += price; |
Common math
const minutes = 135;
const hours = Math.floor(minutes / 60); // 2
const left = minutes % 60; // 15
const r = Math.sqrt(2); // 1.4142135623730951
const area = Math.PI * 3 ** 2;
const whole = Math.trunc(19.99); // 19 (toward zero); Math.floor rounds down
const nearest = Math.round(19.99); // 20
const twoDp = (3.14159).toFixed(2); // "3.14": a STRING, for display
const bigger = Math.max(3, 9, 4); // 9
const dist = Math.abs(-4.5); // 4.5
const dice = Math.floor(Math.random() * 6) + 1; // 1 to 6+ with a string concatenates. "3" + 4 is "34", and "3" * 4 is 12. Numbers that arrive as text (from input, forms or files) must be converted with Number(...) first. TypeScript catches most of these; JavaScript does not.
Strings
const greeting = "Hello";
const n = greeting.length; // 5: a property, no parentheses
const first = greeting[0]; // "H" (positions start at 0; also greeting.charAt(0))
const last = greeting[greeting.length - 1]; // "o" (also greeting.at(-1))
const part = greeting.slice(1, 3); // "el" (from 1 up to, not including, 3)
const where = greeting.indexOf("l"); // 2, or -1 if not found
const loud = greeting.toUpperCase(); // "HELLO"
const both = greeting + ", World"; // concatenation
const msg = `Total: ${3 + 4}`; // template literal: "Total: 7"
const same = greeting === "Hello"; // true: compares the letters
const inside = greeting.includes("ell"); // trueUseful string methods
| Method | Does |
|---|---|
s.toLowerCase(), s.toUpperCase() | Change case |
s.trim() | Remove whitespace at both ends |
s.replace("a", "b"), s.replaceAll("a", "b") | Replace the first / every a |
s.split(",") | An array of pieces |
items.join(", ") | Glue an array of strings together |
s.startsWith("Dr"), s.endsWith(".ts") | Tests |
s.padStart(5, "0") | "42".padStart(5, "0") → "00042" |
s.repeat(3), s.split("").reverse().join("") | Repeat; reverse |
Converting
const count = Number("42"); // 42
const price = parseFloat("3.95"); // 3.95
const n2 = parseInt("42px", 10); // 42: stops at the first bad character
const bad = Number("abc"); // NaN ("not a number"), no error
Number.isNaN(bad); // true: the only reliable NaN test (NaN !== NaN)
const text = String(42); // "42"; or 42.toString() or `${42}`Strings are immutable: greeting[0] = "J" silently does nothing (and is a TypeScript error). Build a new string instead: "J" + greeting.slice(1).
Input and Formatted Output
volume.ts (Node)
import * as readline from "node:readline/promises";
import { stdin, stdout } from "node:process";
const rl = readline.createInterface({ input: stdin, output: stdout });
const bottles = Number(await rl.question("Please enter the number of bottles: "));
const price = Number(await rl.question("Price per bottle: "));
rl.close();
const total = bottles * price;
console.log(`Total: $${total.toFixed(2)} for ${bottles} bottles`);Please enter the number of bottles: 3
Price per bottle: 1.5
Total: $4.50 for 3 bottlesIn a browser
const answer = prompt("Please enter the number of bottles:"); // a string, or null if cancelled
const bottles = Number(answer);
alert(`You asked for ${bottles} bottles`);
// Real pages read <input> elements instead; see the HTML and CSS sheets.Formatting
| Call | Gives |
|---|---|
x.toFixed(2) | "3.50": a string with 2 decimals |
x.toLocaleString() | "1,234,567": thousands separators |
x.toLocaleString("en-US", { style: "currency", currency: "USD" }) | "$4.50" |
s.padStart(8), s.padEnd(10) | Right- and left-align in a column |
console.table(rows) | Prints an array of objects as a table |
Everything that comes from question, prompt, a form or a file is a string. Convert with Number() before doing arithmetic, and check for NaN if the user might type nonsense.
Decisions
Control Flow · TypeScript/JavaScript 1
The if Statement
if (floor > 13) {
actualFloor = floor - 1;
} else if (floor === 13) {
console.log("There is no 13th floor.");
} else {
actualFloor = floor;
}| TypeScript | Math | Note |
|---|---|---|
> >= | > ≥ | |
< <= | < ≤ | |
=== | = | Three equals signs: same type and same value. Always use this one. |
!== | ≠ | Its partner |
==, != | Loose equality converts types first: "5" == 5 is true, 0 == "" is true, null == undefined is true. Avoid. |
| Operator | True when |
|---|---|
a && b | both are true (and) |
a || b | at least one is true (or) |
!a | a is false (not) |
&& and || short-circuit and return one of their operands, not just true or false: name || "Anonymous" is the usual default-value idiom.
Truthiness, Strings and Nothing
if (word === "quit") // strings compare by content
if (word.toLowerCase() === "quit") // ignore case
if (word < other) // by character code (uppercase first); use localeCompare for real alphabetical order
if (word.localeCompare(other) < 0)
const EPSILON = 1e-12;
if (Math.abs(x - y) < EPSILON) // decimals: compare with a tolerance
if (result === undefined || result === null) // "no value"
if (result == null) // the one accepted use of ==: catches both at once
const n = result ?? 0; // nullish coalescing: 0 only when result is null or undefined
const city = user?.address?.city; // optional chaining: undefined instead of a crash| Falsy (counts as false) | Truthy (everything else) |
|---|---|
false, 0, -0, 0n, "", null, undefined, NaN | Non-empty strings, non-zero numbers, all objects and arrays, even [] and {} |
An empty array is truthy. if (items) is always true for an array; ask if (items.length > 0). And || treats 0 and "" as missing: use ?? when zero or an empty string is a real value.
switch and the Conditional Operator
switch
switch (digit) {
case 1:
name = "one";
break;
case 2:
case 3:
name = "two or three";
break;
default:
name = "many";
}
// compares with ===; a missing break FALLS THROUGH into the next caseThe ? : operator
const larger = a > b ? a : b;
const label = n % 2 === 0 ? "even" : "odd";
// condition ? valueIfTrue : valueIfFalseRanges
// Letter grade: each test assumes the earlier ones failed
let grade: string;
if (score >= 90) { grade = "A"; }
else if (score >= 80) { grade = "B"; }
else if (score >= 70) { grade = "C"; }
else { grade = "F"; }Mistakes to Watch For
if (x = 5)assigns and is always true. Neither TypeScript nor JavaScript stops you (tsconly objects when the result cannot be a condition at all); a linter does. Use===and read conditions twice.==instead of===."1" == 1is true and[] == falseis true. Three equals, always.- Testing
0 < x < 10means(0 < x) < 10, which is always true (truebecomes 1). TypeScript catches this one:error TS2365: Operator '<' cannot be applied to types 'boolean' and 'number'. Write0 < x && x < 10. - Declaring
let grade: string;and assigning it in some branches only:error TS2454: Variable 'grade' is used before being assigned.Give it a value up front, or make sure every branch includingelseassigns it. Number("abc")isNaN, and every comparison withNaNis false, includingNaN === NaN. Test withNumber.isNaN(value), or write the condition so that NaN fails it:!(value > 0).- A semicolon right after the condition,
if (x > 0);, ends the if. The block below always runs. - Comparing a number to the string the user typed:
answer >= 18whereansweris"20"happens to work in JavaScript andanswer >= "9"does not. TypeScript refuses both:error TS2365: Operator '>=' cannot be applied to types 'string' and 'number'. Convert first withNumber(answer).
In plain JavaScript: the only difference is that nobody stops you. let grade: string becomes let grade, and every mistake above compiles.
Loops
Control Flow · TypeScript/JavaScript 1
The Loops
| Loop | Use it when | Shape |
|---|---|---|
while | You do not know how many times; stop when a condition changes | while (balance < TARGET) { ... } |
for | You count a known number of times, or need the index | for (let i = 0; i < 10; i++) { ... } |
for ... of | You want each element of an array, string, Set or Map | for (const v of values) { ... } |
do ... while | The body must run at least once | do { ... } while (value <= 0); |
forEach, map, filter | You want to transform or collect; see Lists | values.forEach(v => console.log(v)); |
// while: years until the balance doubles
let year = 0;
while (balance < 2 * initial) { // tested before every turn
year++;
balance = balance + balance * RATE / 100; // moves toward the exit
}
// for: the count is known
for (let i = 1; i <= 10; i++) {
console.log(`${i} squared is ${i * i}`);
}
// for...of: every element, no index
for (const ch of "Hello") {
console.log(ch);
}
// do: at least once
let value: number;
do {
value = Number(await rl.question("Enter a positive number: "));
} while (!(value > 0)); // tested AFTER the body; also rejects NaN1 squared is 1
2 squared is 4
...
10 squared is 100
H
e
l
l
oChoosing a loop
- 1. Do you know before the loop starts how many times it runs, or do you need the index? Use the classic
for. - 2. Do you want every element of an array, string, Set or Map and never its position? Use
for ... of. If you need both,for (const [i, v] of values.entries()). - 3. Are you building a new array from an old one, or keeping some elements? Use
maporfilter(see Lists) instead of a loop withpush. - 4. Otherwise, when the stop depends on something computed as you go (a balance, input, a guess), use
while, and make sure the body changes a variable named in the condition. - 5. Must the body run at least once before the test makes sense (read, then check)? Use
do ... while.
for ... in is not for ... of. for (const i in array) gives the indexes as strings (and any extra properties). For the elements use for ... of; for the keys of an object use Object.keys(obj).
Common Loop Algorithms
Sum, average, count
let total = 0;
let count = 0;
for (const line of lines) {
const v = Number(line);
if (Number.isNaN(v)) { continue; } // skip bad lines
total += v;
count++;
}
const average = count > 0 ? total / count : 0;Maximum and minimum
let largest = values[0]; // start with the first value
for (const v of values) {
if (v > largest) {
largest = v;
}
}
// or: const largest = Math.max(...values); (spread the array into arguments)Sentinel value
let salary = Number(await rl.question("Salary, -1 to finish: "));
while (salary !== -1) {
sum += salary;
salary = Number(await rl.question("Salary, -1 to finish: "));
}Prompting until a flag is set
let done = false;
while (!done) {
const input = await rl.question("> ");
if (input === "Q") {
done = true;
} else {
process(input);
}
}Counting matches
let spaces = 0;
for (const ch of text) {
if (ch === " ") { spaces++; }
}
// or: const spaces = text.split(" ").length - 1;Finding the first match
let position = -1;
for (let i = 0; i < values.length; i++) {
if (values[i] === target) {
position = i;
break;
}
}
// or: const position = values.indexOf(target);Nested Loops and Loop Control
Nested loops: a table
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 4; col++) {
line += String(row * col).padStart(4);
}
console.log(line); // end the row
} 1 2 3 4
2 4 6 8
3 6 9 12entries() for index and value
for (const [i, name] of names.entries()) { // index and value together
console.log(`${i + 1}. ${name}`);
}
names.forEach((name, i) => { // the callback form
console.log(`${i + 1}. ${name}`);
});breakleaves the innermost loop;continueskips to the next turn. Neither works insideforEach: usefor ... ofwhen you need them.- Declare the loop variable with
let(orconstinfor ... of). Avarloop variable leaks out of the loop and is shared by every callback created inside it. - Never change an array while iterating over it; build a new one with
filterormapinstead.
Off-by-One and Other Traps
- Counting from 0 to
n - 1with<, or from 1 tonwith<=. Mixing them runs one time too many or too few. Trace a tiny case (n = 2) by hand. - A loop whose condition never changes is infinite and in a browser freezes the page. Make sure the body moves toward the exit.
- Float counters drift:
for (let x = 0; x !== 1; x += 0.1)never stops. Count with an integer and compute the float inside. values.lengthis re-read every turn; if the body pushes to the array the loop never ends.- The loop variable of a classic
foris already one past the end when the loop finishes. for (let i = 0; i <= items.length; i++)runs one turn too many.items[items.length]isundefined, no error, and the crash comes a line later:TypeError: Cannot read properties of undefined (reading 'toFixed'). Valid positions end atlength - 1, so the test is<.for (const i in items)gives"0","1": strings, not numbers, soi + 1is"01". TypeScript sayserror TS2322: Type 'string' is not assignable to type 'number'if you try to useias one. You almost always wantfor ... of.breakandreturndo not work insideforEach: the callback returns, the loop carries on. Use afor ... ofloop when you may need to stop early.- A semicolon after the header,
for (let i = 0; i < n; i++);, is an empty loop; the block below runs once.
Functions
Control Flow · TypeScript/JavaScript 1
Declaring and Calling
A function packages a computation under a name so you can call it from many places and test it alone. TypeScript adds a type to each parameter and, optionally, to the return value; the compiler then checks every call.
/**
* Computes the volume of a cube.
* @param sideLength the length of one side
* @returns the volume
*/
function cubeVolume(sideLength: number): number {
const volume = sideLength ** 3;
return volume;
}
const result = cubeVolume(2); // the call; 2 is the argument
console.log(result); // 8
cubeVolume("2"); // TypeScript error: string is not assignable to number| Part | In the example | Rules |
|---|---|---|
| Header | function cubeVolume(sideLength: number): number | Name, parameters with types, then the return type after the parentheses |
| Body | between the braces | Runs each time the function is called |
return | return volume; | Ends the call and hands back a value. No return gives undefined; declare that as : void |
| Return type | : number | Optional: TypeScript infers it from the return statements. Writing it documents the intent and catches mistakes inside the body: a path with no return is then error TS2366: Function lacks ending return statement and return type does not include 'undefined'. |
Writing a function, step by step
- 1. Say in one sentence what it computes, and name it for that:
cubeVolume,isValidScore,printReport. - 2. The parameters are the values that differ from call to call, each with a type. Anything you can compute from them belongs in the body.
- 3. Decide what comes back and write it as the return type:
: numberfor a computed value,: booleanfor a test,: voidwhen the function only prints. Do not mix printing and returning in one function. - 4. Write the JSDoc comment, then the body, ending in
return(unlessvoid). - 5. Test it alone with inputs whose answers you know:
cubeVolume(1)is 1,cubeVolume(2)is 8.npx tsxruns the file without a separate compile step.
Mistakes to watch for
- Wrong number of arguments:
cubeVolume()iserror TS2554: Expected 1 arguments, but got 0.In plain JavaScript the missing parameter isundefinedand the result isNaN. - Wrong type:
cubeVolume("2")iserror TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. - A parameter without a type:
function f(x)giveserror TS7006: Parameter 'x' implicitly has an 'any' type.understrict. Write the type. - A misspelled name:
error TS2552: Cannot find name 'totl'. Did you mean 'total'?; at run time in plain JavaScript,ReferenceError: totl is not defined. - Forgetting the parentheses:
console.log(cubeVolume)prints[Function: cubeVolume]instead of calling it. - A
returninside theforloop ends the function on the first turn. Move it after the loop.
Arrow Functions, Defaults and Rest Parameters
Three ways to write a function
function square(x: number): number { // declaration: hoisted, can be called before its line
return x * x;
}
const cube = function (x: number): number { // function expression stored in a const
return x * x * x;
};
const double = (x: number): number => x * 2; // arrow function: short, and keeps the outer this
const greet = (name: string) => { // multi-line arrow: braces and an explicit return
const msg = `Hello, ${name}`;
return msg;
};Default, optional and rest parameters
function greet(name: string, greeting = "Hello", punctuation?: string): string {
return `${greeting}, ${name}${punctuation ?? "!"}`;
}
greet("Ann"); // Hello, Ann!
greet("Ann", "Hi"); // Hi, Ann!
greet("Ann", "Hi", "?"); // Hi, Ann?
function sum(...values: number[]): number { // rest: any number of arguments, as an array
let total = 0;
for (const v of values) { total += v; }
return total;
}
sum(1, 2, 3); // 6
sum(...[4, 5, 6]); // spread an array into argumentsSeveral results
function minMax(values: number[]): [number, number] { // a tuple type
return [Math.min(...values), Math.max(...values)];
}
const [low, high] = minMax([3, 9, 1]); // destructure it
function stats(values: number[]) { // or return an object
return { count: values.length, total: sum(...values) };
}
const { count, total } = stats([1, 2, 3]);Arguments: copies of primitives, references to objects
function addInterest(balance: number, rate: number): void {
balance = balance + balance * rate / 100; // changes the local copy only
}
let savings = 1000;
addInterest(savings, 5);
console.log(savings); // still 1000
function appendBonus(scores: number[]): void {
scores.push(10); // changes the caller's array
}
const myScores = [90, 85];
appendBonus(myScores);
console.log(myScores); // [90, 85, 10]A function cannot make the caller’s variable point at a new value, so for numbers and strings you return the result. It can change the inside of an object or array passed in.
Scope, Closures and Callbacks
Scope
let counter = 0; // module level
function increment(): void {
counter++; // reading and assigning an outer variable is allowed
}
function total(values: number[]): number {
let result = 0; // local: exists only during this call
for (const v of values) { // v is local to the loop
result += v;
}
return result;
}
// let and const are BLOCK scoped: a variable declared inside { } is gone outside itClosures and callbacks
function makeCounter() {
let count = 0; // captured by the function below
return () => {
count++;
return count;
};
}
const next = makeCounter();
next(); // 1
next(); // 2 (count lives on inside the closure)
// Functions are values: pass them to other functions
const numbers = [3, 1, 2];
numbers.sort((a, b) => a - b); // a comparison callback
setTimeout(() => console.log("later"), 1000); // runs after one secondStepwise refinement: write the top level as a list of calls to functions that do not exist yet, each named for one job (readScores, computeAverage, printReport), then write each function. Keep functions short, give each a JSDoc comment, and let TypeScript’s types document the inputs and outputs.
In plain JavaScript: drop the : number annotations and the [number, number] tuple type; everything else, including arrow functions, defaults, rest and spread, destructuring and closures, is plain JavaScript.
Lists: Arrays
Data · TypeScript/JavaScript 1
Creating and Indexing
An array holds a sequence of values in order. Arrays grow and shrink and are mutable. Positions start at 0. In TypeScript an array has an element type, number[] or string[], and the compiler stops you putting the wrong kind in.
const values: number[] = [32, 54, 67.5, 29, 35];
const empty: string[] = []; // annotate an empty array, or TypeScript infers never[]
const zeros = new Array<number>(10).fill(0); // ten zeros
const first = values[0]; // 32
const last = values[values.length - 1]; // 35 (also values.at(-1))
values[1] = 60; // replace
const n = values.length; // 5
values[5]; // undefined: past the end, no error
values[10] = 1; // grows the array; 5 to 9 become empty slots
const middle = values.slice(1, 3); // [60, 67.5]: a new array, from 1 up to 3Visiting every element
for (const v of values) { // the values
console.log(v);
}
for (let i = 0; i < values.length; i++) { // when you need the position
console.log(i, values[i]);
}
for (const [i, v] of values.entries()) { // both
console.log(i, v);
}Common array algorithms
const total = values.reduce((sum, v) => sum + v, 0);
const largest = Math.max(...values);
const average = total / values.length;
const position = values.indexOf(target); // -1 if absent
const found = values.includes(target);
[values[i], values[j]] = [values[j], values[i]]; // swapArray Methods and Aliasing
| Operation | Does | Changes the array? |
|---|---|---|
a.push(x) / a.pop() | Add to / remove from the end | Yes |
a.unshift(x) / a.shift() | Add to / remove from the front | Yes |
a.splice(i, 1), a.splice(i, 0, x) | Remove one at i; insert x at i | Yes |
a.indexOf(x), a.includes(x) | Position of x (-1 if absent); membership | No |
a.slice(from, to) | A copy of part of it | No |
a.sort(cmp), a.reverse() | Sort / reverse in place | Yes |
a.toSorted(cmp), a.toReversed() | Sorted / reversed copies (newer runtimes) | No |
a.concat(b) or [...a, ...b] | A new array of both | No |
a.join(", "), a.flat() | Glue into a string; un-nest one level | No |
Aliasing
const a = [1, 2, 3];
const b = a; // b is another NAME for the same array
b.push(4);
console.log(a); // [1, 2, 3, 4]
const c = [...a]; // a real (shallow) copy; also a.slice()
c.push(5);
console.log(a); // [1, 2, 3, 4]: unchangedconst does not freeze
const nums = [1, 2, 3];
nums.push(4); // fine: the contents changed
nums = [9]; // error: the variable cannot be reassigned
const fixed: readonly number[] = [1, 2, 3];
fixed.push(4); // TypeScript error: readonlyAssignment does not copy an array. After const b = a both names see every change. Copy on purpose with [...a] or a.slice().
Mistakes to watch for
[1, 10, 2, 21].sort()gives[1, 10, 2, 21]: the default sort compares strings. For numbers pass a comparator:.sort((a, b) => a - b).- Reading past the end is silent:
items[5]isundefined, and the crash comes later asTypeError: Cannot read properties of undefined (reading '...'). Checki < items.length. const n = a.push(4)stores the new length (4), not the array; andconst r = a.forEach(...)is alwaysundefined. Usemapwhen you want a result.- Reassigning a
constarray:error TS2588: Cannot assign to 'nums' because it is a constant.; in plain JavaScript,TypeError: Assignment to constant variable.Change the contents, or declare it withlet. - Adding a property TypeScript did not see:
error TS2339: Property 'b' does not exist on type '{ a: number; }'.Declare the full shape with aninterfacefirst. - Removing elements while looping forwards over the same array skips the neighbour of each removed item. Loop backwards, or
filterinto a new array.
map, filter, reduce, Destructuring and Tables
The big three
const squares = [1, 2, 3, 4, 5].map(x => x * x); // [1, 4, 9, 16, 25]
const evens = values.filter(x => x % 2 === 0); // keep the ones that pass
const total = values.reduce((sum, x) => sum + x, 0); // fold to one value
const names = people.map(p => p.name);
const adults = people.filter(p => p.age >= 18);
const found = people.find(p => p.name === "Ann"); // the first match, or undefined
const anyBig = values.some(x => x > 50);
const allPos = values.every(x => x > 0);Destructuring and tuples
const point: [number, number] = [3, 4]; // a tuple: fixed length and types
const [x, y] = point; // unpacking
const [head, ...rest] = [1, 2, 3]; // head = 1, rest = [2, 3]
const pairs: [string, number][] = [["Ann", 90], ["Bob", 85]];
for (const [name, score] of pairs) {
console.log(`${name}: ${score}`);
}Two-dimensional arrays
// A table: an array of rows, each row an array
const table: number[][] = Array.from({ length: 3 }, () => new Array<number>(4).fill(0));
// NOT new Array(3).fill(new Array(4).fill(0)): that shares ONE row three times
table[1][2] = 7;
for (const row of table) {
console.log(row.map(v => String(v).padStart(4)).join(""));
}
const rows = table.length;
const cols = table[0].length;
const columnTotal = table.reduce((sum, row) => sum + row[1], 0);In plain JavaScript: remove : number[], [number, number], readonly and <number>. map, filter, reduce, spread and destructuring are all plain JavaScript.
Files and Exceptions
Data · TypeScript/JavaScript 1
Reading and Writing Text Files (Node)
Browsers cannot touch your disk; file work happens in Node.js through the fs module. The simplest form is synchronous: readFileSync returns the whole file as a string. The promise form with await is what real programs use so they do not freeze while waiting.
lineNumberer.ts
import * as fs from "node:fs";
// Copy input.txt to output.txt with line numbers
const text = fs.readFileSync("input.txt", "utf8");
const lines = text.split(/\r?\n/);
const numbered = lines.map((line, i) => `/* ${i + 1} */ ${line}`);
fs.writeFileSync("output.txt", numbered.join("\n"));| Call | Does |
|---|---|
fs.readFileSync(name, "utf8") | The whole file as a string; throws if it does not exist. Without "utf8" you get raw bytes |
fs.writeFileSync(name, text) | Writes the string; creates the file or erases an existing one |
fs.appendFileSync(name, text) | Adds to the end |
fs.existsSync(name) | Test before opening |
await fs.promises.readFile(name, "utf8") | The same, without blocking; use inside an async function or at the top level of a module |
JSON.parse(text), JSON.stringify(obj, null, 2) | Text to data and back: how most JavaScript programs store structured data. Bad text throws SyntaxError; parse inside try |
Reading a file safely, step by step
- 1. Get the name from
process.argv[2]or the user; it is relative to the working directory. - 2. Read with
readFileSync(name, "utf8")insidetry; a missing file throws, and thecatchis where you tell the user. - 3. Split into lines with
split(/\r?\n/)so Windows line endings do not leave a\ron every line. - 4. Drop blank lines with
filterbefore converting;Number("")is0, which would quietly count as a value. - 5. Convert with
Numberand checkNumber.isNaNper line, so one bad line is reported and skipped.
import * as fs from "node:fs";
const filename = process.argv[2] ?? "numbers.txt";
let text: string;
try {
text = fs.readFileSync(filename, "utf8");
} catch {
console.log(`No such file: ${filename}`);
process.exit(1);
}
let total = 0;
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim();
if (trimmed === "") { continue; } // skip blank lines
const value = Number(trimmed);
if (Number.isNaN(value)) {
console.log(`Skipping bad line: ${trimmed}`);
continue;
}
total += value;
}
console.log(`Total: ${total}`);Taking a line apart
const line = "Smith, Jane, 92";
const parts = line.split(", "); // ["Smith", "Jane", "92"]
const score = Number(parts[2]);
for (const line of lines) {
for (const word of line.trim().split(/\s+/)) { // whitespace-separated words
count++;
}
}Reading numbers
// One number per line, skipping blanks
const values = fs.readFileSync("numbers.txt", "utf8")
.split(/\r?\n/)
.filter(line => line.trim() !== "")
.map(Number);
// JSON: the natural format
const data = JSON.parse(fs.readFileSync("scores.json", "utf8")) as Record<string, number>;
fs.writeFileSync("scores.json", JSON.stringify(data, null, 2));File names are relative to the working directory, the folder you ran node from. Command-line arguments are in process.argv: node prog.js input.txt gives process.argv[2] === "input.txt" (the first two entries are node itself and the script).
Mistakes to watch for
Error: ENOENT: no such file or directory, open 'input.txt'almost always means the working directory is not the folder the file is in. Printprocess.cwd()to see where Node is looking.- Leaving out
"utf8":readFileSync("t.txt")returns aBufferof bytes, printed as<Buffer 34 32 0a>, andsplitdoes not exist on it. TypeScript says so at compile time if you declared the result astring. - Converting the blank last line:
Number("")is0, notNaN, so a trailing newline silently adds a zero to your data. Filter blanks first. JSON.parseon text that is not JSON:SyntaxError: Expected property name or '}' in JSON at position 1. The usual causes are single quotes, a trailing comma or an empty file.writeFileSyncto the file you are reading erases it before the read. Write output under a different name.
Exceptions
When something goes wrong at run time, code throws an error object. If nothing catches it, Node prints the stack trace and stops (in a browser, the page keeps running but the current task dies). You throw your own and catch the ones you can recover from.
Throwing
function withdraw(balance: number, amount: number): number {
if (amount > balance) {
throw new Error("Amount exceeds balance");
}
return balance - amount;
}Catching
try {
const text = fs.readFileSync(filename, "utf8");
const value = JSON.parse(text);
console.log("Read", value);
} catch (e) {
if (e instanceof SyntaxError) {
console.log("Not valid JSON:", e.message);
} else if (e instanceof Error) {
console.log("Could not read:", e.message); // e.g. ENOENT: no such file
} else {
throw e; // something unexpected: let it go
}
}| Built-in error | Thrown when |
|---|---|
Error | The general one; what you usually throw yourself, with a message |
TypeError | Using a value the wrong way: undefined.name, calling something that is not a function |
RangeError | A number out of range: new Array(-1), x.toFixed(200) |
SyntaxError | JSON.parse on bad text |
ReferenceError | A variable that was never declared (a typo) |
In TypeScript the caught value is unknown (anything can be thrown, even a string), so you narrow it with instanceof Error before reading .message.
finally, Custom Errors and async Code
finally and your own error class
class InsufficientFundsError extends Error {
constructor(public readonly balance: number, amount: number) {
super(`Cannot withdraw ${amount}: balance is ${balance}`);
this.name = "InsufficientFundsError";
}
}
try {
balance = withdraw(balance, 500);
} catch (e) {
if (e instanceof InsufficientFundsError) {
console.log("Sorry:", e.message, "Balance:", e.balance);
} else {
throw e;
}
} finally {
console.log("Done"); // runs no matter what
}Errors in async code
import { readFile } from "node:fs/promises";
async function loadScores(name: string): Promise<number[]> {
try {
const text = await readFile(name, "utf8");
return text.split("\n").filter(l => l !== "").map(Number);
} catch (e) {
console.log("Using an empty list:", (e as Error).message);
return [];
}
}
const scores = await loadScores("scores.txt");
// A rejected promise is a thrown error on the await; without await you
// must use .catch(...), or the error is "unhandled" and Node exits.- Throw early: check arguments at the top of a function and throw an
Errorwith a clear message. - Catch late: catch where you can actually do something, often at the top level or around one risky call, not where the problem was found.
- Catch the specific case and rethrow the rest. An empty
catch {}hides bugs. - Throw
Errorobjects, never bare strings: only objects carry a stack trace. - Every
awaiton something that can fail should be inside atry, or the function’s caller shouldawaitit inside one.
In plain JavaScript: remove : number, Promise<number[]>, as Error and as Record<...>; e in a catch is simply whatever was thrown. The public readonly balance shortcut becomes an explicit this.balance = balance.
Sets and Dictionaries: Set, Map and Objects
Data · TypeScript/JavaScript 1
Sets
A Set holds values with no duplicates, in insertion order. Adding a value that is already there does nothing. Use a Set when the question is only “is it in there?” or to collect distinct things.
const names = new Set<string>(["Romeo", "Juliet"]);
names.add("Mercutio");
names.add("Romeo"); // ignored: already present
console.log(names.size); // 3 (a property, like an array's length)
console.log(names.has("Juliet")); // true: very fast
names.delete("Romeo");
for (const name of names) { // insertion order
console.log(name);
}
const distinct = new Set(words); // the distinct words in an array
const asArray = [...distinct]; // back to an array, for sort, map, join...| Operation | Newer runtimes (2024+) | Works everywhere |
|---|---|---|
| Union | a.union(b) | new Set([...a, ...b]) |
| Intersection | a.intersection(b) | new Set([...a].filter(x => b.has(x))) |
| Difference | a.difference(b) | new Set([...a].filter(x => !b.has(x))) |
| Subset test | a.isSubsetOf(b) | [...a].every(x => b.has(x)) |
A Set compares objects by identity, not contents: two different [1, 2] arrays are two members. Store primitives (strings, numbers) or a string key you build from the object.
Maps and Objects as Dictionaries
A Map stores key → value pairs with any type of key, in insertion order. A plain object { } also works as a dictionary with string keys, and is what JSON gives you; TypeScript types it as Record<string, number>. Use Map when you build the dictionary yourself; use an object when the data arrives as JSON or the keys are fixed property names.
const scores = new Map<string, number>();
scores.set("Harry", 90); // add or replace
scores.set("Sally", 95);
const s = scores.get("Harry"); // 90, typed number | undefined
const fred = scores.get("Fred") ?? 0; // 0 instead of undefined
const has = scores.has("Sally");
scores.delete("Harry");
console.log(scores.size);
for (const [name, score] of scores) { // key and value together
console.log(`${name} -> ${score}`);
}
for (const name of scores.keys()) { /* ... */ }
const total = [...scores.values()].reduce((a, b) => a + b, 0);An object as a dictionary
const contacts: Record<string, number> = { Fred: 7235591, Mary: 3841212 };
contacts["Sarah"] = 2213278; // or contacts.Sarah = ...
const n = contacts["Fred"]; // 7235591; undefined if absent
if ("Mary" in contacts) { delete contacts["Mary"]; }
for (const [name, number] of Object.entries(contacts)) {
console.log(name, number);
}
Object.keys(contacts); // ["Fred", "Sarah"]
Object.values(contacts);Counting with a Map
// How many times does each word occur?
const counts = new Map<string, number>();
for (const word of text.toLowerCase().split(/\s+/)) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
// the most common word
let best = "";
let bestCount = 0;
for (const [word, c] of counts) {
if (c > bestCount) { best = word; bestCount = c; }
}
// sorted by count, top three
[...counts].sort((a, b) => b[1] - a[1]).slice(0, 3);Grouping with a Map of arrays
const byLetter = new Map<string, string[]>();
for (const name of names) {
const key = name[0];
if (!byLetter.has(key)) {
byLetter.set(key, []);
}
byLetter.get(key)!.push(name); // ! tells TypeScript we know it exists
}
// newer runtimes: const byLetter = Map.groupBy(names, name => name[0]);
// or with an object: const groups = Object.groupBy(names, name => name[0]);map.get(key) on a missing key returns undefined, and so does obj[key]. TypeScript types the result as number | undefined and makes you handle it (?? 0 or a has check); JavaScript lets it slide until undefined + 1 turns into NaN somewhere else.
Choosing a Collection
| You need | Use |
|---|---|
| Values in order, by position, possibly repeated | an array |
| A fixed group of values with known positions | a tuple: [string, number] |
| Membership only, no duplicates | a Set |
| Look up a value by a key you build at run time | a Map |
| Data from JSON, or a few fixed named fields | an object, typed with an interface or Record |
| First in, first out | an array with push and shift |
| Last in, first out | an array with push and pop |
Deciding, in order
- 1. Will you look values up by a key that is built while the program runs (names read from a file, ids)? A
Map. Remembergetreturnsundefinedfor a missing key; TypeScript types itnumber | undefined, so writem.get(k) ?? 0. - 2. Is the only question “have I seen this before?” A
Set. Note it compares objects and arrays by identity:new Set([[1, 2], [1, 2]]).sizeis 2. - 3. Does position matter, or can the same value appear twice? An array.
- 4. Is it a record with a few fixed, named fields, or data from JSON? A plain object with an
interface. Object keys are always strings:o[[1, 2]]stores under the key"1,2".
In plain JavaScript: remove <string, number>, Record<string, number> and the !; Set, Map, Object.entries and ?? are all plain JavaScript.
Objects, Interfaces and Classes
Objects and Algorithms · TypeScript/JavaScript 1
Objects and Interfaces
JavaScript objects are bags of named properties, written with braces. TypeScript describes their shape with an interface (or a type alias), so the compiler can check that every object has the right fields of the right types. Shapes are checked structurally: any object with those properties fits, whatever it was called.
interface Student {
name: string;
id: number;
email?: string; // optional
readonly enrolled: Date; // cannot be changed after creation
}
const s: Student = { name: "Ann", id: 42, enrolled: new Date() };
console.log(s.name); // dot access
console.log(s["id"]); // bracket access
s.email = "ann@example.edu"; // fine: optional
s.enrolled = new Date(); // TypeScript error: readonly
s.age = 20; // TypeScript error: not in the interface
const { name, id } = s; // destructure
const updated = { ...s, name: "Anne" }; // a copy with one changeClasses
A class is a blueprint: it declares the data each object carries (fields) and what each object can do (methods). An object is one instance, made with new. Use a class when objects carry behavior; use an interface and plain objects when they are just data.
bankAccount.ts
/** A bank account has a balance that can be changed by deposits and withdrawals. */
class BankAccount {
private balance: number; // field: one per object, hidden from outside
/** Constructs a bank account with the given balance (zero by default). */
constructor(initialBalance = 0) {
this.balance = initialBalance;
}
/** Deposits money. */
deposit(amount: number): void {
this.balance += amount;
}
withdraw(amount: number): void {
if (amount > this.balance) {
throw new Error("Amount exceeds balance");
}
this.balance -= amount;
}
/** Gets the current balance. */
getBalance(): number {
return this.balance;
}
toString(): string {
return `BankAccount(balance=${this.balance.toFixed(2)})`;
}
}Using the class
const harrysChecking = new BankAccount(); // constructor with the default
const momsSavings = new BankAccount(5000);
harrysChecking.deposit(2000);
momsSavings.withdraw(500);
console.log(harrysChecking.getBalance()); // 2000
console.log(`${momsSavings}`); // BankAccount(balance=4500.00): template literals call toString
harrysChecking.balance = 0; // TypeScript error: balance is privateThe Pieces of a Class
| Piece | Looks like | Notes |
|---|---|---|
| Field | private balance: number; | Declared at the top; private hides it from code outside the class (a TypeScript check; JavaScript’s own version is #balance) |
| Constructor | constructor(initialBalance = 0) | Runs once when new is called; set every field here. Only one constructor per class; use defaults or unions for variants |
| Method | deposit(amount: number): void | No function keyword inside a class |
this | this.balance | The object the method was called on. Required: a bare balance inside a method is an undeclared variable |
| Getter | get balance(): number { return this._balance; } | Read like a property: acct.balance, no parentheses |
static | static roundCents(x: number) | Belongs to the class: BankAccount.roundCents(3.456); shared counters go here too |
Parameter properties: the short form
class BankAccount {
constructor(private balance = 0, public readonly owner = "unknown") {}
// declares AND assigns both fields in one line
deposit(amount: number): void { this.balance += amount; }
}Objects are references
const a = new BankAccount(1000);
const b = a; // b refers to the SAME object
b.deposit(500);
console.log(a.getBalance()); // 1500
let c: BankAccount | null = null; // refers to nothing
c.deposit(1); // TypeScript error: c is possibly null
c?.deposit(1); // does nothing when c is nullThe this trap: when a method is passed as a callback (button.addEventListener("click", acct.deposit), setTimeout(acct.print, 100)), this is lost. Wrap it in an arrow function, () => acct.print(), or declare the method as an arrow-function field: print = () => { ... }.
Design
Designing a class, step by step
- 1. Write one sentence saying what an object of the class is and what it is responsible for. If that takes two sentences, you have two classes.
- 2. Start with the public interface: what should callers be able to do? Write the method headers and JSDoc comments first; TypeScript’s types do half the documenting.
- 3. Then pick the fields that make those methods possible, mark them
private, and set every one in the constructor. - 4. Add
toString()early, so`${acct}`shows the data instead of[object Object]. (console.log(acct)already printsBankAccount { balance: 5 }.) - 5. Every method should leave the object in a valid state. Test the class alone with a few calls in a scratch file before using it elsewhere.
- 6. Reach for an
interfaceand plain objects when there is no behavior to attach; reach for a class when there is. - 7. Put each class in its own file and
exportit; other filesimport { BankAccount } from "./bankAccount".
Mistakes to watch for
- A bare field name inside a method:
balance += amountgiveserror TS2663: Cannot find name 'balance'. Did you mean the instance member 'this.balance'?It is alwaysthis.balance. - Forgetting
new:BankAccount()iserror TS2348: Value of type 'typeof BankAccount' is not callable. Did you mean to include 'new'?; in plain JavaScript,TypeError: Class constructor BankAccount cannot be invoked without 'new'. - Touching a private field from outside:
error TS2341: Property 'balance' is private and only accessible within class 'BankAccount'.Go through a method or a getter. - Calling a method on a variable that holds nothing:
TypeError: Cannot read properties of null (reading 'deposit'). TypeScript warns first witherror TS18047: 'c' is possibly 'null'.; test, or use?.. - The lost
this(see above) shows up asTypeError: Cannot read properties of undefined (reading 'balance')inside a method that was passed as a callback.
In plain JavaScript: classes, constructors, methods, getters and static are all plain JavaScript. Remove interface blocks, the : type annotations and the words private, public and readonly; write #balance for a truly private field, and assign parameter properties by hand in the constructor.
Inheritance, Interfaces and Unions
Objects and Algorithms · TypeScript/JavaScript 1
Extending a Class
Inheritance builds a new class from an existing one. The subclass gets every method of the superclass and adds or changes what it needs. Read class SavingsAccount extends BankAccount as “a SavingsAccount is a special kind of BankAccount”.
savingsAccount.ts
class SavingsAccount extends BankAccount {
private interestRate: number; // added to what BankAccount has
constructor(rate: number) {
super(); // call the superclass constructor FIRST, before using this
this.interestRate = rate;
}
/** Adds the earned interest to the balance. */
addInterest(): void {
const interest = this.getBalance() * this.interestRate / 100;
this.deposit(interest); // inherited methods, called on this
}
}Overriding
class CheckingAccount extends BankAccount {
private transactionCount = 0;
override deposit(amount: number): void { // same header: replaces the inherited one
this.transactionCount++;
super.deposit(amount); // then do what the superclass does
}
override toString(): string {
return `CheckingAccount(balance=${this.getBalance()}, transactions=${this.transactionCount})`;
}
}The rules
- Call
super(...)before touchingthisin a subclass constructor, or the program throws aReferenceError. - The
overridekeyword is optional but worth it: TypeScript then checks that a method with that exact name exists above. Without it a typo quietly creates a new method. privatefields are not visible to subclasses; useprotectedfor fields a subclass may read, or go through the inherited methods.- Every class ultimately extends
Object, which supplies the defaulttoString.
Polymorphism
const accounts: BankAccount[] = [new BankAccount(100), new SavingsAccount(2.5), new CheckingAccount()];
for (const acct of accounts) {
acct.deposit(10); // the version that runs depends on the actual object
console.log(`${acct}`); // each class's own toString
}
for (const acct of accounts) {
if (acct instanceof SavingsAccount) {
acct.addInterest(); // TypeScript narrows acct to SavingsAccount inside the if
}
}Abstract classes
abstract class Shape {
constructor(public readonly name: string) {}
abstract area(): number; // no body: subclasses must supply it
describe(): string {
return `${this.name} with area ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(private r: number) { super("circle"); }
area(): number { return Math.PI * this.r ** 2; }
}
new Shape("x"); // TypeScript error: cannot create an instance of an abstract class
new Circle(2).describe(); // "circle with area 12.57"Interfaces as contracts
interface Measurable {
getMeasure(): number;
}
class BankAccount implements Measurable {
// ...
getMeasure(): number { return this.getBalance(); }
}
function largest(items: Measurable[]): Measurable {
return items.reduce((best, m) => m.getMeasure() > best.getMeasure() ? m : best);
}
// A class extends ONE class but may implement MANY interfaces.
// Structural typing: any object with a getMeasure(): number method counts, implements or not.Mistakes to watch for
- A subclass constructor that never calls
super(...):error TS2377: Constructors for derived classes must contain a 'super' call.Usingthisbefore it:error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class.In plain JavaScript the same mistake isReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor. new Shape("x"):error TS2511: Cannot create an instance of an abstract class.Create a concrete subclass.- A misspelled override silently adds a new method and the old one still runs. Write
overridein front of every overriding method; a typo then fails witherror TS4117: This member cannot have an 'override' modifier because it is not declared in the base class 'Shape'. Did you mean 'area'? instanceofan interface:error TS2693: 'Measurable' only refers to a type, but is being used as a value here.Interfaces vanish when the code runs; check for the method instead ("getMeasure" in obj) or use a class.
The TypeScript Alternative: Union Types
TypeScript often replaces a class hierarchy with a discriminated union: several plain object shapes that share a kind field, and a switch that handles each. The compiler checks that every case is covered.
interface Circle { kind: "circle"; radius: number; }
interface Square { kind: "square"; side: number; }
type Shape = Circle | Square;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2; // shape is a Circle here
case "square": return shape.side ** 2; // and a Square here
}
}
const shapes: Shape[] = [{ kind: "circle", radius: 2 }, { kind: "square", side: 3 }];
console.log(shapes.map(area));- Use classes and
extendswhen objects carry behavior and state that subclasses specialize. - Use interfaces to say what a thing can do, independent of how it is built.
- Use unions for data that comes in a few fixed shapes, especially data from JSON.
- Equality:
===on two objects means “the very same object”. Write anequals(other)method or compare the fields you care about; there is no operator overloading.
In plain JavaScript: extends, super, instanceof and abstract-by-convention classes are plain JavaScript. interface, implements, abstract, override, type unions and the narrowing all vanish at compile time; in JavaScript a switch on shape.kind still works, it just is not checked for you.
Recursion
Objects and Algorithms · TypeScript/JavaScript 1
A Function That Calls Itself
A recursive function solves a problem by solving a smaller version of the same problem, then doing one more step. Every recursion needs two things: a base case answered directly, and a recursive case that moves toward the base case.
Factorial
function factorial(n: number): number {
if (n <= 1) { // base case
return 1;
}
return n * factorial(n - 1); // recursive case: smaller n
}
// factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * 1 = 24Sum of digits
function digitSum(n: number): number {
if (n < 10) { return n; }
return digitSum(Math.floor(n / 10)) + n % 10; // floor: there is no integer division
}
// digitSum(1729) = digitSum(172) + 9 = (digitSum(17) + 2) + 9 = ((1 + 7) + 2) + 9 = 19Palindrome
function isPalindrome(s: string): boolean {
if (s.length <= 1) { return true; }
if (s[0] !== s[s.length - 1]) { return false; }
return isPalindrome(s.slice(1, -1));
}Thinking recursively
- Trust the recursive call. Assume
isPalindromeworks for shorter strings; your job is only the first and last letter. - Make sure each call is strictly smaller and that the smallest case is handled before any recursive call.
- Trace tiny inputs by hand: the empty string, one character, two characters.
Writing a recursive function, step by step
- 1. State the contract in one line: “
digitSum(n)returns the sum of the digits of n”. Everything below relies on it. - 2. Find the smallest input(s) and return the answer directly. For
digitSumthat is a single digit; for strings and arrays it is usually length 0 or 1. - 3. For any bigger input, peel off one piece (
n % 10,s[0],a[a.length - 1]) and assume the function already works on what is left. - 4. Combine the piece with that result, and
returnit. - 5. Check that every recursive call is strictly smaller and cannot skip past the base case (negative numbers, odd lengths, decimals).
- 6. Test the base case first, then one step above it, then something larger.
Mistakes to watch for
- No base case, or one the input never reaches (
factorial(-1)withn === 0):RangeError: Maximum call stack size exceeded, after about ten thousand calls. - Forgetting
returnbefore the recursive call: the result is dropped and the function returnsundefined. With a declared return type TypeScript catches it:error TS2366: Function lacks ending return statement and return type does not include 'undefined'. digitSum(n / 10)instead ofMath.floor(n / 10):/keeps the fraction, sodigitSum(1729)returns20.919000000000004instead of 19. There is no integer division; useMath.floororMath.trunc.- Big results lose precision above
Number.MAX_SAFE_INTEGER(9007199254740991):factorial(22)prints1.1240007277776077e+21. Usebigint(1n,n * factorial(n - 1n)) when exact large integers matter.
When Recursion Is Slow
// Fibonacci the obvious way: correct, but fib(40) makes over 300 million calls
function fib(n: number): number {
if (n <= 2) { return 1; }
return fib(n - 1) + fib(n - 2);
}
// The same numbers with a loop: n steps
function fibLoop(n: number): number {
let older = 1, old = 1;
for (let i = 3; i <= n; i++) {
[older, old] = [old, older + old];
}
return old;
}
// Or remember answers you already have (memoization)
const memo = new Map<number, number>();
function fibFast(n: number): number {
if (n <= 2) { return 1; }
if (!memo.has(n)) { memo.set(n, fibFast(n - 1) + fibFast(n - 2)); }
return memo.get(n)!;
}- When the recursive case calls itself twice on overlapping problems, the work doubles at every level. Use a loop or memoization.
- Each call uses a stack frame. JavaScript engines stop at roughly ten thousand levels with
RangeError: Maximum call stack size exceeded; a loop would not. - Recursion shines when the problem is naturally nested: permutations, subsets, folders inside folders, the DOM tree of a web page, and “try every choice” searches.
Permutations and Towers of Hanoi
All permutations of a string
function permutations(word: string): string[] {
if (word.length === 0) {
return [""]; // one permutation of the empty string
}
const result: string[] = [];
for (let i = 0; i < word.length; i++) {
const shorter = word.slice(0, i) + word.slice(i + 1);
for (const p of permutations(shorter)) {
result.push(word[i] + p);
}
}
return result;
}
console.log(permutations("eat"));
// ["eat", "eta", "aet", "ate", "tea", "tae"]Towers of Hanoi
/** Moves n disks from source to target using spare. */
function hanoi(n: number, source: string, target: string, spare: string): void {
if (n === 0) { return; }
hanoi(n - 1, source, spare, target);
console.log(`Move disk ${n} from ${source} to ${target}`);
hanoi(n - 1, spare, target, source);
}
hanoi(3, "A", "C", "B"); // 7 moves; n disks take 2 ** n - 1Recursion over a tree: the natural fit
interface Folder { name: string; files: number; subfolders: Folder[]; }
function countFiles(folder: Folder): number {
let total = folder.files;
for (const sub of folder.subfolders) {
total += countFiles(sub); // each subfolder is a smaller version of the same problem
}
return total;
}Mutual recursion is two functions that call each other, such as an expression evaluator where expression() calls term(), which calls factor(), which calls expression() again for a parenthesized part. Function declarations are hoisted, so the order of definition does not matter.
Sorting and Searching
Objects and Algorithms · TypeScript/JavaScript 1
Selection Sort and Insertion Sort
Selection sort
function selectionSort(a: number[]): void {
for (let i = 0; i < a.length - 1; i++) {
let minPos = i; // find the smallest in a[i..]
for (let j = i + 1; j < a.length; j++) {
if (a[j] < a[minPos]) { minPos = j; }
}
[a[i], a[minPos]] = [a[minPos], a[i]]; // swap it into position i
}
}Insertion sort
function insertionSort(a: number[]): void {
for (let i = 1; i < a.length; i++) {
const next = a[i]; // a[0..i-1] is already sorted
let j = i;
while (j > 0 && a[j - 1] > next) { // slide bigger ones right
a[j] = a[j - 1];
j--;
}
a[j] = next; // drop next into the gap
}
}Watch them work
Add console.log(`pass ${i + 1}: [${a.join(", ")}]`); as the last line of the outer loop of selection sort (and pass ${i} in insertion sort) and run each on [11, 9, 17, 5, 12]:
selection sort insertion sort
pass 1: [5, 9, 17, 11, 12] pass 1: [9, 11, 17, 5, 12]
pass 2: [5, 9, 17, 11, 12] pass 2: [9, 11, 17, 5, 12]
pass 3: [5, 9, 11, 17, 12] pass 3: [5, 9, 11, 17, 12]
pass 4: [5, 9, 11, 12, 17] pass 4: [5, 9, 11, 12, 17]Selection sort grows the sorted part from the left by picking the smallest remaining value each pass; insertion sort grows it by sliding the next value into place. Both make about n²/2 comparisons: doubling the array quadruples the time. Insertion sort is fast on data that is already nearly sorted; selection sort always does the same work. Both sort the caller’s array in place, which is why they return void.
Mistakes to watch for
- The built-in
a.sort()without a comparator sorts numbers as strings:[1, 10, 2, 21]stays[1, 10, 2, 21]. Writea.sort((x, y) => x - y). - A comparator that returns
true/false:a.sort((x, y) => x < y)iserror TS2345: Argument of type '(x: number, y: number) => boolean' is not assignable to parameter of type '(a: number, b: number) => number'.; in plain JavaScript it runs and leaves the array unsorted. Return negative, zero or positive. const s = a.sort(...)does not make a copy:sortsortsain place and returns the same array. Usea.toSorted(...)or[...a].sort(...)for a sorted copy.- Inner loop with
j <= a.length:a[j]isundefined, every comparison with it is false, and the sort quietly misbehaves instead of crashing.
Merge Sort
function mergeSort(a: number[]): number[] {
if (a.length <= 1) { return a; }
const mid = Math.floor(a.length / 2);
const first = mergeSort(a.slice(0, mid)); // sort each half
const second = mergeSort(a.slice(mid));
return merge(first, second); // then merge them
}
function merge(first: number[], second: number[]): number[] {
const merged: number[] = [];
let i = 0, j = 0;
while (i < first.length && j < second.length) {
if (first[i] < second[j]) { merged.push(first[i++]); }
else { merged.push(second[j++]); }
}
return merged.concat(first.slice(i), second.slice(j)); // whatever is left over
}
// returns a NEW sorted array: const sorted = mergeSort(values);| Algorithm | Comparisons for n items | Big-O | Doubling n makes it |
|---|---|---|---|
| Selection sort | about n²/2 | O(n²) | 4 times slower |
| Insertion sort | n²/4 average; n if already sorted | O(n²) | 4 times slower |
| Merge sort | about n log2 n | O(n log n) | a little more than 2 times slower |
Array.prototype.sort (TimSort in V8) | n log n worst, n if already sorted; stable | O(n log n) | a little more than 2 times slower |
| Linear search | n/2 average, n worst | O(n) | 2 times slower |
| Binary search (sorted data) | about log2 n | O(log n) | one more step |
Big-O keeps only the fastest-growing term and drops constants: 3n² + 20n + 7 is O(n²). It describes how the work scales, not how many seconds it takes.
Searching
Linear search
function linearSearch(a: number[], value: number): number {
for (let i = 0; i < a.length; i++) {
if (a[i] === value) { return i; }
}
return -1;
}
// built in: a.indexOf(value), a.includes(value), a.find(x => ...), a.findIndex(x => ...)Binary search (the array must be sorted)
function binarySearch(a: number[], value: number): number {
let low = 0;
let high = a.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (a[mid] === value) { return mid; }
else if (a[mid] < value) { low = mid + 1; }
else { high = mid - 1; }
}
return -1;
}
// 1,000,000 sorted items: at most 20 stepsThe library does it faster, with one famous trap
[10, 9, 1].sort(); // [1, 10, 9] !!! sorts as STRINGS by default
[10, 9, 1].sort((a, b) => a - b); // [1, 9, 10] ascending numbers
values.sort((a, b) => b - a); // descending
const sorted = values.toSorted((a, b) => a - b); // a sorted copy (newer runtimes); or [...values].sort(...)
names.sort((a, b) => a.localeCompare(b)); // alphabetical, accents and case handled
names.sort((a, b) => a.length - b.length); // by another rule
people.sort((a, b) => a.age - b.age); // objects, by one field
people.sort((a, b) => a.last.localeCompare(b.last) || a.first.localeCompare(b.first)); // by twosort() with no comparator sorts everything as strings. [10, 9, 1].sort() gives [1, 10, 9]. Always pass (a, b) => a - b for numbers. The comparator must return a negative number, zero or a positive number, never a boolean.
Sorting your own objects
class Country {
constructor(public readonly name: string, public readonly area: number) {}
/** Negative, zero or positive: the natural order, by area. */
compareTo(other: Country): number {
return this.area - other.area;
}
}
countries.sort((a, b) => a.compareTo(b));
countries.sort((a, b) => a.name.localeCompare(b.name)); // or any other ordercompareTo vs a comparator
- A
compareTomethod in the class gives one natural order; there is no built-in interface for it, so you still pass(a, b) => a.compareTo(b). - A comparator arrow function picks any order for one call, without touching the class.
- JavaScript’s sort is stable: items that compare equal keep their original order, so you can sort by last name after sorting by first name.
In plain JavaScript: remove : number[], : void and the public readonly shortcut. The string-sorting trap, localeCompare, toSorted and stable sorting are all JavaScript behavior.