Skip to content
HopperHopper

Course navigation

Phase 2 · Data and functionsDay 8

Functions, part 1

  • About 65 minutes
  • 9 sections
  • Runnable TypeScript examples
  • Practice questions

Before you start

About 65 minutes

By the end you will be able to

  1. Declare a function with typed parameters and a return type, call it, and predict what it gives back or shows.
  2. Choose between a required, optional, and default parameter, and read the checker's message for a wrong call.
  3. Explain local scope, and why a function should return a new value instead of changing its arguments.
  4. Write short arrow functions, return early from a function, and add a doc comment that the editor shows on hover.

What to remember from earlier

Section 1 of 9

8.1 Declaring and Calling a Function

Before you start, set up a new project folder named day08 exactly as you set up day01 in 1.2: open the folder in VS Code, run npm init -y and npm install --save-dev typescript in its terminal, and type the same tsconfig.json. Every program today goes in that folder.

Since Day 1 you have been calling functions that someone else wrote: console.log shows a value, Math.floor rounds one down, "abc".toUpperCase() makes capitals. Each one is a named job. You hand it an argument, it does its work, and you never see the lines inside it. Today you write functions of your own, and that changes how you build programs. Instead of one long list of statements, you name each job once and use it as often as you need.

Why does that matter? Picture a café program that welcomes each guest with two lines. For three guests, that is six console.log lines, and when the wording changes, you must fix it in three places. A function is a named block of statements that runs only when it is called. You write the two lines once, give them a name, and call the name three times. Here is the whole thing:

Worked example: Welcoming guests

welcome.ts
function welcome(name: string) {
  console.log(`Welcome, ${name}!`);
  console.log("Your table is ready.");
}

welcome("Ana");
welcome("Ben");
console.log("Doors close at 22:00.");
welcome("Chi");
Welcome, Ana!
Your table is ready.
Welcome, Ben!
Your table is ready.
Doors close at 22:00.
Welcome, Chi!
Your table is ready.

Lines 1 to 4 are the function declaration. Take it apart:

Piece What it is
function The keyword that starts a declaration
welcome The function’s name, in camelCase like a variable. It usually names an action: welcome, showOrder
(name: string) The parameter list: a variable that is created each time the function is called, with its type
{ ... } The body: the statements that run on each call

A declaration on its own does nothing. When Node reads lines 1 to 4, it learns what welcome means and moves on; nothing is shown yet. Line 6 is the first call, welcome("Ana"), and here is what happens, step by step: the program jumps to line 1, creates the parameter name holding the argument "Ana", runs line 2 and line 3, reaches the closing } on line 4, and returns to line 6, where it carries on with the next statement. The order of the output shows the jumps: line 8 does not run until the call on line 7 has finished, and the last call, on line 9, prints after the “Doors close” line.

Order Line What happens
1 1–4 Node learns the declaration; nothing runs
2 6 Call: jump to line 1 with name holding "Ana"
3 2–3 Show two lines, then return to line 6
4 7 Call again: a fresh name holding "Ben"
5 2–3 Show two lines, then return to line 7
6 8 Show Doors close at 22:00.
7 9 Call: name holding "Chi"; two lines; return

The word for the value in the call, "Ana", is the same as on Day 1: an argument. The word for the variable that receives it, name, is a parameter. A parameter is a placeholder written in the declaration; an argument is the real value handed over in a call. Each call gets its own fresh name.

Now vary the number of parameters. Separate them with commas, and give each its own type:

show-order.ts
function showOrder(item: string, quantity: number) {
  console.log(`${quantity} x ${item}`);
}

showOrder("coffee", 2);
showOrder("bagel", 1);
const drinks: number = 3;
showOrder("tea", drinks + 1);
2 x coffee
1 x bagel
4 x tea

The arguments are matched to the parameters by position: in showOrder("coffee", 2), the first argument goes to the first parameter, item, and the second to quantity. On line 8, the argument drinks + 1 is an expression. It is worked out first, to 4, and only the value is handed over; the function never sees the name drinks.

Why must every parameter have a type? Inside showOrder, the checker needs to know what item and quantity are to check how they are used. Unlike a variable, a parameter has no starting value to infer a type from, because the value arrives later, from whoever calls the function. So you write the type yourself, and the checker then does two jobs with it: it checks the body as if quantity were any number, and it checks every call, rejecting an argument of the wrong type or a missing one.

Key idea

function name(parameter: type, ...) {body} declares a function; nothing runs until it is called. A call hands arguments to the parameters by position, runs the body, then returns to the line after the call. Every parameter needs a type.

Watch out

Leaving a parameter’s type off. In strict mode the checker refuses to guess:

no-type.ts
function welcome(name) {
  console.log(`Welcome, ${name}!`);
}

welcome("Ana");
no-type.ts:1:18 - error TS7006: Parameter 'name' implicitly has an 'any' type.

any is a type that means “could be anything, do not check,” and strict mode does not let it appear by accident. Column 18 is the parameter itself. Write name: string and the message goes away. Fix or delete the file before your next check.

Calling with the wrong arguments. The checker compares every call with the declaration:

bad-calls.ts
function showOrder(item: string, quantity: number) {
  console.log(`${quantity} x ${item}`);
}

showOrder(2, "coffee");
showOrder("bagel");
bad-calls.ts:5:11 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
bad-calls.ts:6:1 - error TS2554: Expected 2 arguments, but got 1.

Line 5 has the arguments in the wrong order, so the first argument, a number, lands on item, which wants a string. TS2345 names the argument’s type, then the parameter’s: read it as “you gave a number where a string was required.” (The checker reports only the first mismatched argument on a line.) Line 6 leaves quantity out, and TS2554 counts for you. Neither program would run as the writer intended, so the checker stops both. Fix or delete this file too.

Pause and try

Question 1 · Tracing

Predict exactly what this program shows, in order.

predict-calls.ts
function cheer(team: string, times: number) {
  for (let i = 1; i <= times; i++) {
    console.log(`Go ${team}!`);
  }
}

console.log("Kickoff");
cheer("Lions", 2);
cheer("Owls", 1);
console.log("Final whistle");
Check your reasoning
Kickoff
Go Lions!
Go Lions!
Go Owls!
Final whistle

Lines 1 to 5 only declare cheer; nothing is shown until line 7. Line 8 calls cheer with team holding "Lions" and times holding 2, so the loop inside runs twice and shows Go Lions! twice, then the program returns to line 8 and moves on to line 9, which shows one Go Owls!. Line 10 runs last.

Reread 8.1 Declaring and Calling a Function if any line differed.

Question 2 · Multiple choice

showOrder is declared as function showOrder(item: string, quantity: number). Which call does npx tsc accept?

  1. showOrder("tea", "2");
  2. showOrder(2, "tea");
  3. showOrder("tea", 2);
  4. showOrder("tea");
Check your reasoning

C. The first argument is a string and the second a number, matching the parameters by position.

  • A is wrong: "2" in quotes is a string, and quantity wants a number, so TS2345.
  • B is wrong: the arguments are swapped, so a number lands on item: TS2345.
  • D is wrong: quantity is missing, so TS2554, “Expected 2 arguments, but got 1.”

Reread 8.1 Declaring and Calling a Function if you chose differently.

Section 2 of 9

8.2 Returning a Value

welcome and showOrder do their job by showing text. But most functions you have called so far give back a value instead: Math.floor(7.8) gives 7, and you decide what to do with it, store it, show it, or add to it. A function of your own can do the same, and that is what makes functions fit together: one works out a value, another uses it.

The statement that gives a value back is return. When the program reaches return expression; inside a function, it works out the expression, leaves the function at once, and hands the value to the call. The call then becomes that value, exactly as 4 + 5 becomes 9: you can store it, show it, or use it inside a bigger expression.

Worked example: The area of a rectangle

rectangle-area.ts
function rectangleArea(width: number, height: number): number {
  return width * height;
}

const floor = rectangleArea(4, 3);
console.log(`Floor: ${floor} square metres`);
console.log(`Wall: ${rectangleArea(5, 2.5)} square metres`);
console.log(`Both: ${rectangleArea(4, 3) + rectangleArea(5, 2.5)}`);
Floor: 12 square metres
Wall: 12.5 square metres
Both: 24.5

Two things are new in line 1. After the parameter list comes : number, the return type: a promise that every return in this function hands back a number. And the body, line 2, is a single return. Follow line 5: the call rectangleArea(4, 3) jumps to line 1 with width holding 4 and height holding 3, line 2 works out 4 * 3 and returns 12, and back on line 5, the call becomes 12, which is stored in floor. Hover over floor in VS Code and it shows const floor: number: the checker knows the type of a call’s result from the return type.

Line 7 puts a call straight into a template literal, and line 8 adds the results of two calls. Each call is worked out first, like the parentheses in arithmetic, and then the values are added.

Now vary the type. A function can return a string, built from locals inside it, and it can return a boolean, which makes it a question you can ask in an if:

price-label.ts
function priceLabel(name: string, price: number): string {
  const formatted = price.toFixed(2);
  return `${name}: $${formatted}`;
}

console.log(priceLabel("Tea", 2.5));
console.log(priceLabel("Bagel", 3));
Tea: $2.50
Bagel: $3.00

Line 2 declares a constant inside the function and line 3 returns a template literal that uses it. The return type says : string, so the checker confirms that the template literal is a string. If you leave the return type off, the checker infers it from the return statements, and hovering over the name shows function priceLabel(name: string, price: number): string. This course writes return types anyway: they tell a reader what to expect without reading the body, and, as the Watch Out below shows, they catch a wrong return.

is-even.ts
function isEven(n: number): boolean {
  return n % 2 === 0;
}

const seats: number = 14;
if (isEven(seats)) {
  console.log("Everyone gets a partner.");
}
console.log(isEven(7));
Everyone gets a partner.
false

n % 2 === 0 is already a boolean, so line 2 returns it directly. Line 6 then uses the call as a condition: isEven(seats) becomes true, so the block runs. A function that returns a boolean is usually named like a question, isEven, hasSpace, canVote, so that an if reads as English.

Key idea

return expression; leaves the function at once and hands the value to the call, which becomes that value. The return type after the parameter list, such as : number, promises what kind of value comes back, and the checker holds every return to it.

Watch out

Returning the wrong kind of value. Here the writer promised a number and returned text:

return-string.ts
function half(n: number): number {
  return `${n / 2}`;
}

console.log(half(9));
return-string.ts:2:3 - error TS2322: Type 'string' is not assignable to type 'number'.

This is Day 1’s TS2322, pointing at the return on line 2: a template literal is a string, and the function promised a number. Remove the backticks and ${}, return n / 2;, or change the promise. Without the : number, the checker would have inferred string and accepted the function, and the mistake would have surfaced later, far from its cause. Fix or delete the file before your next check.

Code after return. Anything in the body after a return that always runs can never be reached:

after-return.ts
function total(price: number, quantity: number): number {
  return price * quantity;
  console.log("Calculating...");
}

console.log(total(3, 4));
12

Line 3 never shows Calculating..., because line 2 has already left the function. npx tsc accepts the file, and VS Code shows line 3 in grey to warn you. Put statements that must run before the return.

Pause and try

Question 3 · Tracing

Predict exactly what this program shows.

predict-return.ts
function discount(price: number, percent: number): number {
  return price - (price * percent) / 100;
}

const sale = discount(80, 25);
console.log(sale);
console.log(discount(sale, 50));
console.log(discount(10, 0) + 1);
Check your reasoning
60
30
11
  • Line 5: discount(80, 25) works out 80 - (80 * 25) / 100, which is 80 - 20, and returns 60, stored in sale.
  • Line 7: the argument is sale, so the call is discount(60, 50): 60 - 30 is 30.
  • Line 8: discount(10, 0) returns 10 - 0, which is 10, and then + 1 is applied to the result: 11.

Reread 8.2 Returning a Value if any line differed.

Question 4 · Multiple choice

What does npx tsc say about this program?

half-string.ts
function half(n: number): number {
  return n / 2;
}

const result: string = half(9);
console.log(result);
  1. Nothing; node then shows 4.5
  2. TS2322 on line 5: a number is not assignable to type string
  3. TS2345 on line 5: a number is not assignable to a parameter of type string
  4. TS2322 on line 2: a number is not assignable to type number
Check your reasoning

B. The call half(9) becomes a number, because that is the function’s return type, and line 5 tries to store that number in a constant annotated string. That is Day 2’s rule for assignments, and the message is Day 1’s:

half-string.ts:5:7 - error TS2322: Type 'number' is not assignable to type 'string'.
  • A is wrong: the types do not fit, so the checker reports it, even though node would happily run the file.
  • C is wrong: TS2345 is about an argument not fitting a parameter; the argument 9 fits n: number perfectly.
  • D is wrong: n / 2 is a number, and the function promised a number, so line 2 is fine.

If you typed this program, fix or delete it. Reread 8.2 Returning a Value if you chose differently.

Section 3 of 9

8.3 Functions That Return Nothing: void

Not every function has a value to give back. welcome in 8.1 shows two lines and that is its whole job. What is its return type? There is a type for “this function gives back nothing useful”: void. A function with return type void has no return expression; at all, and a call to it is a statement on its own, like console.log(...), rather than an expression you store.

Worked example: Printing receipt lines

print-line.ts
function printLine(item: string, price: number): void {
  console.log(`${item.padStart(6)}: ${price.toFixed(2).padStart(6)}`);
}

printLine("Coffee", 3.5);
printLine("Bagel", 2.25);
printLine("Juice", 4);
Coffee:   3.50
 Bagel:   2.25
 Juice:   4.00

printLine does its work on line 2 by showing text, with Day 3’s toFixed and padStart padding the name and the price to fixed widths so that the columns line up. It has nothing to return, so line 1 says : void, and the body has no return. Lines 5 to 7 are three calls, each a statement by itself. The checker would infer void if you left the annotation off; writing it tells a reader at once that this function is called for what it does, not for what it gives back.

What if you do store the result of a void function? Vary print-line.ts by catching the result of a call:

void-result.ts
function sayHi(name: string): void {
  console.log(`Hi, ${name}!`);
}

const result = sayHi("Ana");
console.log(result);
Hi, Ana!
undefined

Line 5 runs the call first, so Hi, Ana! appears, and then stores what came back. A function that reaches its closing } without a return gives back Day 2’s undefined, the value that means “nothing was assigned.” The checker allows the assignment (hover over result: const result: void) but there is never a reason to write it. Call a void function as a statement, and call a function with a real return type where you need its value.

Key idea

A function whose job is an effect, such as showing text, returns nothing: declare it : void, write no return expression;, and call it as a statement. A function that reaches its end without a return gives back undefined.

Watch out

Forgetting the return. The writer meant double(4) to be 8:

forgot-return.ts
function double(n: number) {
  n * 2;
}

console.log(double(4));
undefined

Line 2 works out n * 2 and then throws the result away, because nothing stores or returns it. The function reaches its end and gives back undefined, which is what line 5 shows. npx tsc accepts this, because with no return type written, it infers void and the body fits. Now add the return type you meant:

forgot-return-typed.ts
function double(n: number): number {
  n * 2;
}

console.log(double(4));
forgot-return-typed.ts:1:29 - error TS2355: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.

With : number promised, the checker notices that no path through the body returns anything, and points at the return type (column 29). This is the strongest reason to write return types: undefined where you expected a number is a bug that otherwise shows up only when the program runs. The fix is return n * 2;. Fix or delete both files before your next check.

Pause and try

Question 5 · Tracing

Predict exactly what this program shows, including the last line.

predict-void.ts
function shout(text: string): void {
  console.log(text.toUpperCase() + "!");
}

function exclaim(text: string): string {
  return text + "!";
}

shout("ready");
const line = exclaim("set");
console.log(line);
console.log(shout("go"));
Check your reasoning
READY!
set!
GO!
undefined
  • Line 9: shout("ready") shows READY! and returns nothing.
  • Lines 10 and 11: exclaim("set") returns "set!", which is stored and then shown.
  • Line 12: the inner call runs first, so shout("go") shows GO!; it gives back undefined, and the outer console.log shows that.

Reread 8.3 Functions That Return Nothing: void if any line differed.

Question 6 · Multiple choice

Which of these functions should be declared with return type void?

  1. One that works out the tip for a restaurant bill
  2. One that shows a formatted receipt in the terminal
  3. One that reports whether a word is a palindrome
  4. One that joins a first name and a last name
Check your reasoning

B. Showing a receipt is an effect: the function’s job is done once the text is on the screen, and there is nothing to hand back.

  • A is wrong: a tip is a number the caller needs, so the function returns number.
  • C is wrong: “whether” means a yes-or-no answer, a boolean the caller will test in an if.
  • D is wrong: the joined name is a string the caller will show or store.

Reread 8.3 Functions That Return Nothing: void if you chose differently.

Section 4 of 9

8.4 Optional Parameters and Default Values

A greeting function needs a name and a greeting word. But nearly every call will use "Hello", and typing it each time is tiresome. It would be better if callers could leave the greeting out and get "Hello" unless they say otherwise. TypeScript gives you two ways to let a caller leave an argument out, and they differ in what the parameter holds when that happens.

The first is a default value: write = value after the parameter, and the function uses that value whenever the caller gives none.

Worked example: A greeting with a default

default-greeting.ts
function greet(name: string, greeting = "Hello"): string {
  return `${greeting}, ${name}!`;
}

console.log(greet("Ana"));
console.log(greet("Ben", "Good morning"));
console.log(greet("Chi", undefined));
Hello, Ana!
Good morning, Ben!
Hello, Chi!

Line 1 writes greeting = "Hello" with no type annotation. The checker infers the type string from the default: hover over greet and it shows function greet(name: string, greeting?: string): string, where the question mark means “the caller may leave this out.” Line 5 calls with one argument, so greeting holds "Hello". Line 6 gives a second argument, which replaces the default. Line 7 passes undefined on purpose, and the default is used for that too: undefined means “no value,” so the function treats it the same as a missing argument. Inside the body, greeting is always a string; the default makes sure of that.

The second way is an optional parameter: write ? after the name, as in subtitle?: string. The caller may leave it out, and when they do, the parameter holds undefined, with no default to replace it. Use this when “nothing was given” is itself meaningful and the function must behave differently:

book-label.ts
function bookLabel(title: string, subtitle?: string): string {
  return subtitle === undefined ? title : `${title}: ${subtitle}`;
}

console.log(bookLabel("Dune"));
console.log(bookLabel("Salt", "A World History"));
Dune
Salt: A World History

A book with no subtitle should show just its title, not Dune: undefined, so the function must find out whether a subtitle arrived. Line 2 asks subtitle === undefined, the same kind of check as Day 4’s === null, and the conditional operator picks the plain title or the joined one. Hover over subtitle in VS Code and it shows string | undefined, read “a string or undefined,” the type Day 3 previewed for at(); Day 9 teaches it fully. After the === undefined check, the checker knows the other branch has a real string.

Why not always write ? instead of a default? Because inside the function, an optional parameter might be undefined, and the checker will not let you forget that:

optional-arithmetic.ts
function tip(bill: number, percent?: number): number {
  return (bill * percent) / 100;
}

console.log(tip(40));
optional-arithmetic.ts:2:18 - error TS18048: 'percent' is possibly 'undefined'.

This is Day 3’s message for at(), for the same reason: undefined times a number makes no sense, so the checker refuses until you check for it, or give a default. For a percentage, a default is the right tool, percent = 15, and then percent is always a number. Fix or delete the file before your next check.

Parameter Written as Caller may leave it out? Inside the function it holds
Required name: string No (TS2554) A string
With a default greeting = "Hello" Yes The argument, or "Hello"
Optional subtitle?: string Yes The argument, or undefined

One rule governs both: parameters that may be left out come after every required one. The arguments are matched by position, so if an optional parameter came first, the checker could not tell which parameter a lone argument was meant for.

Key idea

greeting = "Hello" gives a parameter a default, so the caller may leave it out and the function still has a value. subtitle?: string makes it optional, and it holds undefined when left out, which the function must check for. Both come after the required parameters.

Watch out

An optional parameter before a required one. The checker rejects the declaration itself:

optional-first.ts
function greet(greeting?: string, name: string): string {
  return `${greeting}, ${name}!`;
}

console.log(greet("Hi", "Ana"));
optional-first.ts:1:35 - error TS1016: A required parameter cannot follow an optional parameter.

Column 35 is the required parameter name. Swap them, name: string, greeting?: string, and fix the call to match. Fix or delete the file.

Too many arguments. The checker counts the other way too:

too-many.ts
function greet(name: string, greeting = "Hello"): string {
  return `${greeting}, ${name}!`;
}

console.log(greet("Ana", "Hi", "!"));
too-many.ts:5:32 - error TS2554: Expected 1-2 arguments, but got 3.

The range 1-2 tells you the function has one required parameter and one that may be left out. A third argument, the "!" at column 32, has no parameter to land on. Day 10 shows a way to accept any number of arguments; for now, fix or delete the file.

Pause and try

Question 7 · Tracing

Predict exactly what this program shows. For each call, decide what every parameter holds first.

predict-defaults.ts
function repeatWord(word: string, times = 2, separator = " "): string {
  let result = word;
  for (let i = 1; i < times; i++) {
    result += separator + word;
  }
  return result;
}

console.log(repeatWord("ho"));
console.log(repeatWord("no", 3));
console.log(repeatWord("yes", 2, "-"));
console.log(repeatWord("hi", undefined, "/"));
Check your reasoning
ho ho
no no no
yes-yes
hi/hi
Line word times separator Loop adds Result
9 "ho" 2 " " one " ho" ho ho
10 "no" 3 " " two " no" no no no
11 "yes" 2 "-" one "-yes" yes-yes
12 "hi" 2 "/" one "/hi" hi/hi

Line 12 passes undefined for times to reach the third parameter, so times takes its default, 2. The loop on line 3 starts at 1 and runs while i < times, so it adds the word times - 1 more times after the first.

Reread 8.4 Optional Parameters and Default Values if any line differed.

Question 8 · Multiple choice

Mo wants callers to be able to write both tip(40) and tip(40, 15), and wants percent to always be a number inside the function. Which header does that?

  1. function tip(bill: number, percent?: number): number
  2. function tip(bill: number, percent = 15): number
  3. function tip(percent = 15, bill: number): number
  4. function tip(bill: number, percent: number): number
Check your reasoning

B. A default lets the caller leave percent out and still makes it a number inside, 15 when nothing is given.

  • A is wrong: both calls are accepted, but inside the function percent may be undefined, and bill * percent is rejected with TS18048 until it is checked.
  • C is wrong: tip(40) would hand 40 to percent and leave bill missing, TS2554. A parameter with a default belongs after the required ones.
  • D is wrong: both parameters are required, so tip(40) is TS2554.

Reread 8.4 Optional Parameters and Default Values if you chose differently.

Section 5 of 9

8.5 Local Scope

priceLabel in 8.2 declared a constant, formatted, inside its body. Where does that constant live, and who can see it? On Day 4 you met scope, the part of a program where a name can be used, and learned that a variable declared inside an if block exists only inside that block. A function body is a block too, and the same rule applies, with one more thing added: the parameters belong to the body as well.

A variable declared inside a function, and every parameter, is local to that function: it is created when the call starts, it can be used only inside the body, and it is gone when the function returns. The space outside every function, where today’s programs declare their constants and make their calls, is the outer scope.

Worked example: Two locals and two parameters

describe-order.ts
function describeOrder(quantity: number, unitPrice: number): string {
  const subtotal = quantity * unitPrice;
  const tax = subtotal * 0.1;
  return `Total: ${(subtotal + tax).toFixed(2)}`;
}

console.log(describeOrder(3, 2.5));
console.log(describeOrder(1, 10));
Total: 8.25
Total: 11.00

While the call on line 7 is running, four local names exist: the parameters quantity (3) and unitPrice (2.5), and the constants subtotal (7.5) and tax (0.75). Line 4 uses them to build the string, returns it, and all four vanish. Line 8 then calls again, and fresh locals are created: quantity is 1, unitPrice is 10, subtotal is 10, tax is 1. Nothing from the first call is left over. Each call starts from a clean slate, which is why a function behaves the same every time.

While line 7 runs Value While line 8 runs Value
quantity 3 quantity 1
unitPrice 2.5 unitPrice 10
subtotal 7.5 subtotal 10
tax 0.75 tax 1

Try to use one of those names from outside, and the checker reports Day 1’s TS2304, just as it did for an if block’s variable on Day 4:

scope-leak.ts
function describeOrder(quantity: number, unitPrice: number): string {
  const subtotal = quantity * unitPrice;
  return `Total: ${subtotal.toFixed(2)}`;
}

console.log(describeOrder(3, 2.5));
console.log(subtotal);
console.log(quantity);
scope-leak.ts:7:13 - error TS2304: Cannot find name 'subtotal'.
scope-leak.ts:8:13 - error TS2304: Cannot find name 'quantity'.

By line 7 the call has finished and subtotal no longer exists; and quantity, a parameter, was never visible outside the body either. If the outer code needs the value, the function must return it. Fix or delete the file before your next check.

Scope works in one direction. The outer scope cannot see into a function, but a function can see the outer scope. A constant declared at the top of the file can be read inside any function below it:

tax-rate.ts
const taxRate = 0.1;

function withTax(price: number): number {
  return price + price * taxRate;
}

console.log(withTax(20));
console.log(withTax(5));
22
5.5

taxRate is not a parameter and not a local, so when line 4 uses it, the program looks outward, finds the constant on line 1, and reads 0.1. This is how a function uses a setting shared by the whole program. The function could take the rate as a parameter instead; that is the better choice when different calls need different rates.

Now vary it: what if a local has the same name as an outer variable?

shadow.ts
let total = 100;

function addBonus(points: number): number {
  const total = points + 10;
  return total;
}

console.log(addBonus(5));
console.log(total);
15
100

Line 4 declares a new constant named total inside the function. Inside the body, that name means the local one, 15, and the outer total is hidden for those lines; programmers say the local shadows it. Line 9 shows that the outer total is still 100: the function never touched it, because const total = ... on line 4 made a new variable instead of assigning to the outer one. Shadowing is allowed, but it is confusing to read, so give locals their own names.

Key idea

Parameters and variables declared in a function body are local: created on each call, usable only inside, gone after the return. A function can read names from the outer scope, but the outer scope cannot see inside a function; to get a value out, return it.

Watch out

Expecting a local to survive the call. Students often declare a result inside a function and then try to show it outside, as in scope-leak.ts. The checker catches it with TS2304, but the real fix is a habit: a function hands values out only through return, and the caller stores what comes back in its own variable: const result = describeOrder(3, 2.5);.

Pause and try

Question 9 · Tracing

Predict exactly what this program shows. There are two variables named count.

predict-scope.ts
let count = 0;

function bump(amount: number): number {
  const count = amount * 2;
  return count;
}

console.log(bump(3));
console.log(count);
count = bump(1) + count;
console.log(count);
Check your reasoning
6
0
2
  • Line 8: bump(3) makes a local count holding 6 and returns it: 6.
  • Line 9: the outer count was never changed by the call, because line 4 declared a new local rather than assigning. It is still 0.
  • Line 10: bump(1) returns 2, and 2 + count is 2 + 0; the outer count becomes 2, which line 11 shows.

Reread 8.5 Local Scope if any line differed.

Question 10 · Debugging

Sam’s program should show the average, then the sum. npx tsc rejects it. Predict the message, explain it, and fix the program without moving the function.

average-debug.ts
function average(a: number, b: number): number {
  const sum = a + b;
  return sum / 2;
}

console.log(average(4, 8));
console.log(`Sum was ${sum}`);
Check your reasoning
average-debug.ts:7:24 - error TS2304: Cannot find name 'sum'.

sum is a local of average: it exists only while a call is running, and by line 7 the call on line 6 has finished and returned. The outer scope never had a sum. The function returns the average, not the sum, so the outer code must work out the sum itself, or the function must return it. Here is one fix that keeps average as it is:

average-debug-fixed.ts
function average(a: number, b: number): number {
  const sum = a + b;
  return sum / 2;
}

const first: number = 4;
const second: number = 8;
console.log(average(first, second));
console.log(`Sum was ${first + second}`);
6
Sum was 12

If you typed the broken version, fix or delete it before you go on.

Reread 8.5 Local Scope if you missed it.

Section 6 of 9

8.6 Arrow Functions

Some functions are tiny: square a number, halve it, add a dollar sign. Writing function, a name, braces, and return for a one-line job takes four lines for one idea. TypeScript has a shorter way to write a function, and you will see it everywhere in TypeScript code, so you need to read it as easily as the long form.

An arrow function is a function written as an expression, with => (an equals sign and a greater-than sign, read “arrow”) between its parameters and its body. Because it is an expression, you store it in a constant, and the constant’s name becomes the function’s name.

Worked example: Two one-line helpers

square-arrow.ts
const square = (n: number): number => n * n;
const half = (n: number): number => n / 2;

console.log(square(6));
console.log(half(square(3)));
36
4.5

Take line 1 apart:

Piece What it is
const square = A constant that will hold the function; its name is how you call it
(n: number) The parameter list, exactly as in a declaration, with types
: number The return type, written after the parameters
=> The arrow, separating the header from the body
n * n An expression body: this expression’s value is returned, with no return keyword

Calling is the same as before: line 4 works out square(6) and shows 36, and line 5 passes the result of one call to another. Hover over square and VS Code shows const square: (n: number) => number. That is how the checker writes the type of a function, with an arrow too; Day 10 puts that notation to work.

When the body needs more than one expression, give it braces. A block body is just like a declaration’s body: statements, and a return to hand back the value:

initials-arrow.ts
const initials = (first: string, last: string): string => {
  const letters = first[0] + last[0];
  return letters.toUpperCase();
};

console.log(initials("grace", "hopper"));
GH

With braces, return is required again, and so is the semicolon after the closing brace on line 4, because the whole thing is a const statement. The rule of thumb: an expression body for a one-expression function; a block body, or a plain function declaration, for anything longer. Both kinds of function do the same thing when called. This course uses declarations for the main jobs of a program and arrow functions for small helpers.

There is one real difference, in when the function exists. A function declaration is known to the whole file from the start, even above the lines that declare it:

before-declaration.ts
console.log(triple(2));

function triple(n: number): number {
  return n * 3;
}
6

Line 1 calls triple before line 3 declares it, and that works, because Node reads every declaration before running anything. An arrow function stored in a const does not get that treatment: a const exists only from its line onward, as on Day 2.

before-arrow.ts
console.log(triple(2));

const triple = (n: number): number => n * 3;
before-arrow.ts:1:13 - error TS2448: Block-scoped variable 'triple' used before its declaration.
before-arrow.ts:1:13 - error TS2454: Variable 'triple' is used before being assigned.

Both messages say the same thing: on line 1, triple has not been given its value yet. Move the call below the const, then fix or delete the file. This is why helpers written as arrow functions usually sit near the top of a file.

Key idea

const name = (parameter: type): returnType => expression; is an arrow function: a function stored in a constant, whose expression body is returned automatically. With braces it needs return. Declarations can be called from above their line; a const cannot.

Watch out

Braces without return. Adding braces turns the body into a block, and a block does not return its last expression:

arrow-no-return.ts
const cube = (n: number): number => {
  n ** 3;
};

console.log(cube(2));
arrow-no-return.ts:1:27 - error TS2355: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.

This is 8.3’s message: the body works out n ** 3 and throws it away, and the promised number never comes back. Either remove the braces, => n ** 3, or write return n ** 3; inside them. Fix or delete the file before your next check.

Pause and try

Question 11 · Tracing

Predict exactly what this program shows.

predict-arrow.ts
const double = (n: number): number => n * 2;
const greet = (name: string): string => `Hey ${name}`;
const area = (w: number, h: number): number => {
  const result = w * h;
  return result;
};

console.log(double(double(5)));
console.log(greet("Lu"));
console.log(area(3, 4) + double(1));
Check your reasoning
20
Hey Lu
14
  • Line 8: the inner double(5) is 10, and double(10) is 20.
  • Line 9: the expression body is a template literal: Hey Lu.
  • Line 10: area(3, 4) runs its block body and returns 12; double(1) is 2; 14.

Reread 8.6 Arrow Functions if any line differed.

Question 12 · Multiple choice

Which arrow function does exactly what function cube(n: number): number { return n ** 3; } does, and passes npx tsc?

  1. const cube = (n: number): number => n ** 3;
  2. const cube = (n: number): number => { n ** 3; };
  3. const cube = (n) => n ** 3;
  4. function cube = (n: number): number => n ** 3;
Check your reasoning

A. An expression body returns its value, so n ** 3 comes back as the promised number.

  • B is wrong: the braces make a block body with no return, so TS2355, as in the Watch Out.
  • C is wrong: n has no type, so TS7006 from 8.1.
  • D is wrong: function starts a declaration, which has a name and braces, never = and an arrow; the checker reports a syntax error.

Reread 8.6 Arrow Functions if you chose differently.

Section 7 of 9

8.7 Return Early Instead of Nesting

A shipping function has rules in layers: members ship free; otherwise, up to 1 kg costs $4, up to 5 kg costs $8, and anything heavier costs $15. Written with Day 4’s if and else, each rule sits inside the previous one’s else:

shipping-nested.ts
function shippingCost(weightKg: number, isMember: boolean): number {
  let cost: number;
  if (isMember) {
    cost = 0;
  } else {
    if (weightKg <= 1) {
      cost = 4;
    } else {
      if (weightKg <= 5) {
        cost = 8;
      } else {
        cost = 15;
      }
    }
  }
  return cost;
}

console.log(shippingCost(3, false));
8

It works, but reading it means keeping track of three levels of braces, and cost has to be a let that every branch remembers to assign. Now use what 8.2 taught: return leaves the function at once. That means a function can deal with one case and leave, and the code after it only ever runs for the cases that are left:

Worked example: The same rules, flat

shipping-early.ts
function shippingCost(weightKg: number, isMember: boolean): number {
  if (isMember) {
    return 0;
  }
  if (weightKg <= 1) {
    return 4;
  }
  if (weightKg <= 5) {
    return 8;
  }
  return 15;
}

console.log(shippingCost(3, true));
console.log(shippingCost(0.5, false));
console.log(shippingCost(3, false));
console.log(shippingCost(12, false));
0
4
8
15

Each if on lines 2, 5, and 8 handles one case and returns. There is no else anywhere, because none is needed: if line 3 ran, the function is already over, so line 5 is reached only by non-members. Follow the call on line 16, shippingCost(3, false): line 2 is false, so skip to line 5; 3 <= 1 is false, skip to line 8; 3 <= 5 is true, return 8. Line 11 is the final answer for everyone who got past every check. The let is gone too, since each branch returns its value directly.

An if that checks a case and returns is called a guard clause: it guards the rest of the function from that case. Reading the function top to bottom, each guard clause removes one case from your mind, and by the end you know exactly who is left.

Guard clauses are also the natural way to handle bad input. An average function should not divide by zero when the list is empty:

average-guard.ts
function average(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  let total = 0;
  for (const score of scores) {
    total += score;
  }
  return total / scores.length;
}

console.log(average([80, 90, 100]));
console.log(average([]));
90
0

Line 2 checks the one case that would go wrong, an empty array, and returns 0 for it; the loop below runs only when there is something to add up. average([]) on line 13 returns 0 instead of 0 / 0, which would be NaN. Put the guard clauses first, then the main work.

Key idea

A guard clause is an if that handles one case and returns. Stack guard clauses at the top of a function, each returning for its case, and let the last line return for everyone who is left; no else and no nesting are needed.

Watch out

A path with no return. With guard clauses, every path through the function must still reach a return:

missing-path.ts
function sign(n: number): string {
  if (n > 0) {
    return "positive";
  }
  if (n < 0) {
    return "negative";
  }
}

console.log(sign(0));
missing-path.ts:1:27 - error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

The writer covered positive and negative but forgot zero: for sign(0), both conditions are false, the function reaches its end, and undefined would come back instead of a string. The checker reads every path and points at the return type (column 27). Add a last line, return "zero";, that handles whoever is left. Fix or delete the file before your next check.

Pause and try

Question 13 · Tracing

Predict exactly what this program shows. The order of the guard clauses matters.

predict-early.ts
function ticketPrice(age: number, isStudent: boolean): number {
  if (age < 5) {
    return 0;
  }
  if (isStudent) {
    return 6;
  }
  if (age >= 65) {
    return 7;
  }
  return 10;
}

console.log(ticketPrice(3, true));
console.log(ticketPrice(20, true));
console.log(ticketPrice(70, false));
console.log(ticketPrice(70, true));
console.log(ticketPrice(30, false));
Check your reasoning
0
6
7
6
10
  • Line 14: age 3 is under 5, so the first guard returns 0; being a student is never checked.
  • Line 15: not under 5; a student, so 6.
  • Line 16: not under 5, not a student, 70 is at least 65: 7.
  • Line 17: 70 but a student. The student guard comes before the age check, so it returns 6 first.
  • Line 18: every guard is false, so the last line returns 10.

Reread 8.7 Return Early Instead of Nesting if any line differed.

Section 8 of 9

8.8 Pure Functions and Changing Arguments

In 8.5 you saw that a function cannot create variables in the outer scope. But can it change things out there? That depends on what kind of value it was handed, and the difference is one of the most important things to understand about functions.

Start with a number. The parameter is a new local variable, and it receives a copy of the value:

Worked example: A copy of a number

add-ten.ts
function addTen(n: number): number {
  n = n + 10;
  return n;
}

let score = 5;
const bigger = addTen(score);
console.log(score, bigger);
5 15

Line 7 calls addTen(score). The value 5 is copied into the parameter n; n and score are two separate variables that happen to hold the same number. Line 2 changes n to 15 and line 3 returns it. Back outside, score is still 5, as line 8 shows. Nothing a function does to a number, string, or boolean parameter can reach the caller’s variable, because the parameter only ever held a copy.

Now hand over an array instead. On Day 6 you learned that push changes an array in place, and that making a separate copy takes slice or [...items]. A variable holding an array does not hold the elements themselves; it holds a link to one array that lives elsewhere. Passing the array to a function copies the link, not the array:

push-shared.ts
function addBonus(scores: number[]): void {
  scores.push(100);
}

const myScores = [70, 85];
addBonus(myScores);
console.log(myScores);
[ 70, 85, 100 ]

After line 6’s call, myScores has three elements. Inside the call, the parameter scores and the outer myScores were two names for the same array, so line 2’s push changed the one array they both pointed at. The same is true of Day 7’s objects: a function given an object can change its properties, and the caller sees the change.

What is passed What the parameter holds A change inside the function…
number, string, boolean A copy of the value Stays inside; the caller sees nothing
array or object A link to the same array or object Is seen by the caller

Is changing the caller’s array a bug? Sometimes it is exactly the point, but it is a surprise to anyone reading addBonus(myScores); who expected their scores to be left alone. A function that depends only on its arguments, and changes nothing outside itself, is called a pure function: call it twice with the same arguments and you get the same result, and nothing else in the program is different afterwards. Pure functions are easy to reason about, because you can read their body alone, and easy to test (Day 22). Here is the pure version of addBonus:

with-bonus.ts
function withBonus(scores: readonly number[]): number[] {
  const result = [...scores];
  result.push(100);
  return result;
}

const myScores = [70, 85];
const boosted = withBonus(myScores);
console.log(myScores);
console.log(boosted);
[ 70, 85 ]
[ 70, 85, 100 ]

Line 2 copies the array with the spread operator, line 3 pushes onto the copy, and line 4 returns it. The caller’s array, shown on line 9, is untouched, and the caller stores the new one in boosted. Notice readonly number[] on line 1. It is a promise to callers that the function will not change the array it is given, and the checker enforces the promise, as it did for Day 6’s readonly arrays:

readonly-push.ts
function addBonus(scores: readonly number[]): void {
  scores.push(100);
}

addBonus([70, 85]);
readonly-push.ts:2:10 - error TS2339: Property 'push' does not exist on type 'readonly number[]'.

With readonly in the header, a push on the parameter is rejected before the program runs. Write readonly on every array parameter you do not intend to change; it costs nothing and it catches an accidental push, pop, or splice. (A caller may pass a plain number[] to a readonly number[] parameter; the promise is one way.) Fix or delete the file before your next check.

The other way a function can be impure is by changing an outer let:

running-total.ts
let total = 0;

function addToTotal(amount: number): number {
  total += amount;
  return total;
}

console.log(addToTotal(5));
console.log(addToTotal(5));
5
10

total += amount on line 4 does not declare a new local, so it assigns to the outer variable from line 1, and the change lasts. The same call, addToTotal(5), gives 5 the first time and 10 the second: not pure. Programs do need some values that change over time, and Day 19 shows how to organize that in a web page. Until then, prefer functions that take what they need as parameters and return their result, and keep the few variables that must change in the outer scope, changed by lines that are easy to find.

Key idea

A number, string, or boolean argument is copied into the parameter, so the function cannot change the caller’s variable. An array or object argument is shared, so push or a property change inside the function is seen outside. A pure function changes nothing outside itself: it copies, builds a new value, and returns it. Mark array parameters readonly to have the checker enforce that.

Watch out

Assigning to the parameter instead of changing the array. This function is meant to empty the caller’s cart:

clear-cart.ts
function clear(items: string[]): void {
  items = [];
}

const cart = ["milk", "eggs"];
clear(cart);
console.log(cart);
[ 'milk', 'eggs' ]

Line 2 points the local name items at a brand-new empty array. The caller’s array is not emptied; the function has only changed which array its own parameter refers to, and that local is gone after the call. Changing the array’s contents, with push, pop, or splice, reaches the caller; assigning a new array to the parameter never does. The clearer design is pure anyway: return the new array, and let the caller write cart = clear(cart); with a let.

Pause and try

Question 14 · Tracing

Predict exactly what this program shows. Decide for each call whether the caller’s value can change.

predict-shared.ts
function rename(name: string): string {
  name = name.toUpperCase();
  return name;
}

function addItem(list: string[], item: string): number {
  list.push(item);
  return list.length;
}

let city = "lima";
const loud = rename(city);
console.log(city, loud);

const bag = ["pen"];
const size = addItem(bag, "book");
console.log(bag, size);
Check your reasoning
lima LIMA
[ 'pen', 'book' ] 2
  • Line 12: rename receives a copy of "lima". Line 2 reassigns the local name and line 3 returns it, so loud is "LIMA", but city is still "lima" (line 13). Strings are never changed in place anyway, as Day 3 taught; a new string was made.
  • Line 16: addItem receives a link to the same array as bag. Line 7’s push changes that array, so bag now has two elements, and the function returns the new length, 2.

Reread 8.8 Pure Functions and Changing Arguments if any line differed.

Question 15 · Multiple choice

Which of these functions is pure?

  1. function nextId(): number { lastId++; return lastId; }, where lastId is an outer let
  2. function tax(price: number): number { return price * 0.2; }
  3. function addZero(list: number[]): void { list.push(0); }
  4. function announce(text: string): void { console.log(text); }
Check your reasoning

B. tax depends only on its argument and returns a new value; the same price always gives the same tax, and nothing else changes.

  • A is wrong: it changes an outer let, and two calls with the same (empty) arguments give different results.
  • C is wrong: it changes the array it was given, which the caller sees.
  • D is wrong: showing text is a change to the outside world, the terminal. It returns nothing, and it is called for its effect, which is fine, but it is not pure.

Reread 8.8 Pure Functions and Changing Arguments if you chose differently.

Section 9 of 9

8.9 Doc Comments

Once a program has several functions, you call most of them without rereading their bodies. What does discounted expect: a fraction like 0.2, or a percentage like 20? What does it give back for a discount over 100? A good name helps, but a sentence helps more, and TypeScript has a kind of comment that your editor shows to you at exactly the moment you need it: when you hover over the function’s name, or start typing a call.

A doc comment is a block comment that starts with /** (a slash and two stars) and sits directly above a function. Day 1’s ordinary block comment starts with /* and one star; the second star is what makes VS Code treat the text as documentation.

Worked example: Documenting a discount

doc-comment.ts
/**
 * Works out the price after a percentage discount.
 *
 * @param price the original price
 * @param percent the discount, from 0 to 100
 * @returns the discounted price, never below 0
 */
function discounted(price: number, percent: number): number {
  const result = price - (price * percent) / 100;
  if (result < 0) {
    return 0;
  }
  return result;
}

console.log(discounted(50, 20));
console.log(discounted(50, 150));
40
0

Lines 1 to 7 are the doc comment. Line 2 is a one-sentence summary of what the function does. After a blank line come tags, each starting with @:

Tag What it says
@param name text What that parameter means, in what units, and any limits
@returns text What comes back, including what happens in edge cases

The stars at the start of each middle line are a convention that lines the comment up; VS Code adds them for you when you press Enter inside a doc comment. Node and the checker skip the comment entirely, as they do every comment, so the program runs exactly as before: discounted(50, 20) is 40, and the guard clause on line 10 turns discounted(50, 150), which would be -25, into 0, exactly as line 6 promised.

Now hover over discounted on line 16 in VS Code. The box shows the function’s header, then the summary, then each parameter’s description. Type discounted( on a new line and the same text appears as you fill in the arguments. The comment is written once and read every time anyone, including you next week, calls the function.

A doc comment can sit above an arrow function’s const too, and it may be as short as a single line when the function is simple:

doc-arrow.ts
/** Formats an amount of money with a dollar sign and two decimal places. */
const money = (amount: number): string => `$${amount.toFixed(2)}`;

/**
 * Builds one line of a price list.
 *
 * @param name the product name
 * @param price the price in dollars
 */
const priceLine = (name: string, price: number): string => `${name}: ${money(price)}`;

console.log(priceLine("Notebook", 4.5));
Notebook: $4.50

Line 1 is a one-line doc comment: /**, the sentence, */. Lines 4 to 9 document the second helper with tags. Either way, hovering over money or priceLine shows the text.

What should a doc comment say? What the function does and what the caller must know: the meaning and units of each parameter, the limits (from 0 to 100), and what comes back in unusual cases (never below 0, 0 when there are none). Not how the body works, which the body already shows. And keep it true: a comment that promises something the code no longer does is worse than none, because readers trust it.

Key idea

A doc comment, /** ... */, directly above a function is shown by the editor whenever the function is hovered or called. Give a one-sentence summary, then @param for each parameter and @returns for the result, saying what, in what units, with what limits.

Watch out

One star instead of two. /* Works out the discount. */ is an ordinary block comment. The program runs the same, but hover over the function and nothing appears, because only /** marks documentation. The difference is one character, so check for the second star when a hover shows only the header.

Pause and try

Question 16 · Short answer

Write a doc comment for this function, with a summary, a @param for each parameter, and a @returns line. Then check that your program still runs the same.

function countChar(text: string, target: string): number {
  let count = 0;
  for (const ch of text) {
    if (ch === target) {
      count++;
    }
  }
  return count;
}
Check your reasoning

One good version:

doc-answer.ts
/**
 * Counts how many times a character appears in a text.
 *
 * @param text the text to search; case matters
 * @param target one character to look for
 * @returns the number of matches, 0 when there are none
 */
function countChar(text: string, target: string): number {
  let count = 0;
  for (const ch of text) {
    if (ch === target) {
      count++;
    }
  }
  return count;
}

console.log(countChar("banana", "a"));
console.log(countChar("banana", "z"));
3
0

The summary says what the function does in one sentence. The @param lines tell the caller two things the header cannot: that case matters, and that target should be a single character. The @returns line names the edge case, 0 when nothing matches, so the caller knows not to expect -1 as indexOf would give. Your wording may differ; a complete answer must:

  • start with /** and sit directly above function,
  • summarize what the function does, not how the loop works, and
  • say what each parameter means and what comes back.

Reread 8.9 Doc Comments if yours differed.

Wrap-up · 1 of 8

Putting it together

A café receipt program: items with a name, price, and quantity, a student or staff discount code that may be missing, and 8% tax. Every job is a small function with a doc comment, and only one of them shows anything. Before you type it, make sure npx tsc is clean in your day08 folder: fix or delete any broken file from today.

cafe-receipt.ts
type Item = { name: string; price: number; quantity: number };

const taxRate = 0.08;

/** Formats an amount of money with a dollar sign and two decimal places, such as -$1.50. */
const money = (amount: number): string => {
  const sign = amount < 0 ? "-" : "";
  const size = amount < 0 ? -amount : amount;
  return `${sign}$${size.toFixed(2)}`;
};

/**
 * Works out the total for one line of the receipt.
 *
 * @param item the item ordered
 * @returns price times quantity
 */
function lineTotal(item: Item): number {
  return item.price * item.quantity;
}

/**
 * Adds up the line totals.
 *
 * @param items the items ordered; an empty order totals 0
 */
function subtotal(items: readonly Item[]): number {
  let total = 0;
  for (const item of items) {
    total += lineTotal(item);
  }
  return total;
}

/**
 * Works out the discount to take off.
 *
 * @param amount the subtotal
 * @param code the discount code, if the customer gave one
 * @returns the discount in dollars; 0 for no code or an unknown code
 */
function discountFor(amount: number, code?: string): number {
  if (code === undefined) {
    return 0;
  }
  if (code === "STUDENT") {
    return amount * 0.2;
  }
  if (code === "STAFF") {
    return amount * 0.5;
  }
  return 0;
}

/** Prints one receipt line: a label, then the amount lined up on the right. */
function printLine(label: string, amount: number): void {
  console.log(`${label.padStart(10)} ${money(amount).padStart(8)}`);
}

/**
 * Prints the whole receipt for an order.
 *
 * @param items the items ordered
 * @param code the discount code, if any
 */
function printReceipt(items: readonly Item[], code?: string): void {
  for (const item of items) {
    printLine(`${item.quantity} x ${item.name}`, lineTotal(item));
  }
  const before = subtotal(items);
  const discount = discountFor(before, code);
  const tax = (before - discount) * taxRate;
  printLine("Subtotal", before);
  if (discount > 0) {
    printLine("Discount", -discount);
  }
  printLine("Tax", tax);
  printLine("Total", before - discount + tax);
}

const order: Item[] = [
  { name: "latte", price: 3.5, quantity: 2 },
  { name: "bagel", price: 2.25, quantity: 1 },
];

printReceipt(order, "STUDENT");

npx tsc reports no errors, and node cafe-receipt.ts shows:

 2 x latte    $7.00
 1 x bagel    $2.25
  Subtotal    $9.25
  Discount   -$1.85
       Tax    $0.59
     Total    $7.99

Follow the last line, printReceipt(order, "STUDENT"), into the functions it calls:

Line What happens Idea
1 A type alias for one item; Item[] and readonly Item[] use it below Day 7
3 An outer constant every function below can read 8.5
6–10 An arrow helper with a block body; the conditional operator handles negative amounts 8.6
66 items is readonly, and code is optional, so it may be undefined 8.8, 8.4
67–69 One printLine call per item; lineTotal(item) is worked out first, then handed over 8.1, 8.2
70 subtotal loops over the items and returns 9.25; the array is never changed 8.8
71 discountFor(9.25, "STUDENT"): the first guard is passed, the second returns 1.85 8.7
72 (9.25 - 1.85) * 0.08 is 0.592 8.5
73–78 Four more printLine calls, each a void call as a statement; -discount prints as -$1.85 8.3

Each function does one job and says so in its doc comment. lineTotal, subtotal, discountFor, and money are pure: give them the same arguments and they return the same value, and none of them touches the order. The two print functions are void, called for what they show. Change the order, or pass "STAFF" or no code at all, and only the numbers change; the functions stay the same.

Wrap-up · 2 of 8

Common mistakes

Today’s messages and silent surprises in one place. The first group comes from npx tsc; the second shows no message at all.

Message or symptom Usual cause Fix
TS7006: Parameter 'name' implicitly has an 'any' type. A parameter with no type name: string
TS2345: Argument of type 'number' is not assignable to parameter of type ... An argument of the wrong type, or arguments in the wrong order Match each argument to its parameter
TS2554: Expected 2 arguments, but got 1. Too few or too many arguments Match the count; add a default or ?
TS2322: Type 'string' is not assignable to type 'number'. at a return Returning a value of the wrong type Return the promised type, or change the promise
TS2355: A function whose declared type is neither ... must return a value. No return in a function with a return type; braces without return Add return
TS2366: Function lacks ending return statement ... A path through the function with no return Add a final return for the cases left
TS18048: 'percent' is possibly 'undefined'. Doing arithmetic with an optional parameter Use a default, or check === undefined
TS1016: A required parameter cannot follow an optional parameter. ? or = on a parameter before a required one Required parameters first
TS2304: Cannot find name 'sum'. Using a local or parameter outside the function return it and store the result
TS2448: Block-scoped variable 'triple' used before its declaration. Calling an arrow function above its const Move the call below
TS2339: Property 'push' does not exist on type 'readonly number[]'. Changing a readonly parameter Copy with [...items] first
undefined shows where a value was expected A return forgotten, or a void call stored Write the return type; call void as a statement
The caller’s array changed push on an array parameter Copy, change the copy, return it
The caller’s variable did not change Assigning to a parameter (n = n + 10, items = []) Return the new value and store it
Hover shows no description /* with one star /**
Wrap-up · 3 of 8

Vocabulary

Term Definition Example
function declaration function name(parameters) { body }: names a block of statements to run on each call function welcome(name: string) { ... }
parameter A variable in the header that receives an argument on each call; always typed name: string
argument The value handed over in a call, matched to a parameter by position "Ana" in welcome("Ana")
body The statements between the function’s braces { console.log(...); }
call / return Running a function / coming back to the line after the call welcome("Ana");
return Leaves the function at once and hands a value to the call return width * height;
return type The promised type of the returned value, after the parameter list : number
void The return type of a function that gives nothing back function printLine(...): void
default value = value on a parameter, used when the caller gives none greeting = "Hello"
optional parameter ? on a parameter; it holds undefined when left out subtitle?: string
local A parameter or variable that exists only inside a function, for one call const subtotal = ... in a body
outer scope The part of the file outside every function const taxRate = 0.1;
shadow A local with the same name as an outer variable hides it inside the function const total inside, let total outside
arrow function A function written as an expression with =>, stored in a constant const square = (n: number): number => n * n;
expression body / block body An arrow body that returns its expression / one with braces and return => n * n / => { return n * n; }
guard clause An if that handles one case and returns, so the rest of the function ignores it if (isMember) { return 0; }
pure function Depends only on its arguments and changes nothing outside itself withBonus returns a new array
doc comment /** ... */ above a function, shown by the editor on hover, with @param and @returns /** Works out the tip. */
Wrap-up · 4 of 8

Summary

  • A function declaration names a block of statements; a call hands arguments to its typed parameters by position, runs the body, and comes back. return leaves at once with a value, and the return type is a promise the checker keeps: TS2322 for a wrong value, TS2355 for none.
  • A function with nothing to give back is void: call it as a statement. A function that reaches its end without return gives undefined.
  • A default value (greeting = "Hello") fills in a missing argument; an optional parameter (subtitle?: string) holds undefined instead, which the function must check. Both come after the required parameters.
  • Parameters and variables inside a function are local: fresh on each call, gone after the return, invisible outside (TS2304). A function can read the outer scope. Arrow functions are short functions stored in constants, so they exist only from their line onward.
  • A guard clause handles one case and returns, so stacked ifs replace nested elses; every path still needs a return (TS2366).
  • Numbers, strings, and booleans are copied into parameters; arrays and objects are shared, so push inside changes the caller’s array. A pure function copies, builds, and returns instead, and readonly on a parameter makes the checker enforce that. A doc comment (/** ... */) tells callers what a function does, right in the editor.
Wrap-up · 5 of 8

Practice

Do these in your day08 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (such as no-type.ts, bad-calls.ts, return-string.ts, forgot-return-typed.ts, optional-arithmetic.ts, optional-first.ts, too-many.ts, scope-leak.ts, before-arrow.ts, arrow-no-return.ts, missing-path.ts, readonly-push.ts, or the questions’ half-string.ts and average-debug.ts), fix it or delete it. Then write each program yourself, check it with npx tsc, run it with node, and only then open the answer. Give every function a return type and a doc comment, and test it with several calls, including an edge case.

Question 17 · Short answer

Prime check. Write isPrime(n: number): boolean, which returns whether n is prime: a whole number greater than 1 whose only divisors are 1 and itself. Call it for several numbers, including 1 and 2, and show each result.

Check your reasoning

One possible solution:

is-prime.ts
/**
 * Reports whether a whole number is prime: greater than 1, and divisible only by 1 and itself.
 *
 * @param n the number to test
 */
function isPrime(n: number): boolean {
  if (n < 2) {
    return false;
  }
  for (let divisor = 2; divisor < n; divisor++) {
    if (n % divisor === 0) {
      return false;
    }
  }
  return true;
}

for (const candidate of [1, 2, 9, 17, 25, 97]) {
  console.log(`${candidate}: ${isPrime(candidate)}`);
}
1: false
2: true
9: false
17: true
25: false
97: true

The guard clause on line 7 handles numbers below 2, which are never prime, and returns at once. The loop on line 10 tries every possible divisor from 2 up to n - 1; the moment one divides n exactly (Day 2’s % gives 0), line 12 returns false and the loop is abandoned. Only a number that survives every divisor reaches line 15. For 2, the loop’s condition 2 < 2 is false immediately, so 2 goes straight to return true. The calling loop at the bottom uses Day 6’s for...of over an array of test values.

Reread 8.7 Return Early Instead of Nesting and 8.2 Returning a Value if your result differed.

Question 18 · Short answer

Temperature list. Write a function that takes an array of temperatures in Fahrenheit and returns a new array of the same temperatures in Celsius, leaving the original unchanged. Use a second function to convert one temperature. Show both arrays to prove the original is untouched. (Celsius is (fahrenheit - 32) * 5 / 9.)

Check your reasoning

One possible solution:

to-celsius.ts
/** Converts one temperature from Fahrenheit to Celsius. */
function toCelsius(fahrenheit: number): number {
  return ((fahrenheit - 32) * 5) / 9;
}

/**
 * Converts a list of temperatures from Fahrenheit to Celsius.
 *
 * @param readings temperatures in Fahrenheit; left unchanged
 * @returns a new array of the same length, in Celsius
 */
function convertAll(readings: readonly number[]): number[] {
  const result: number[] = [];
  for (const reading of readings) {
    result.push(toCelsius(reading));
  }
  return result;
}

const fahrenheit = [32, 212, 50, 77, -40];
const celsius = convertAll(fahrenheit);
console.log(fahrenheit);
console.log(celsius);
[ 32, 212, 50, 77, -40 ]
[ 0, 100, 10, 25, -40 ]

toCelsius is a pure one-line function, and convertAll is pure too: it starts an empty array on line 13, pushes one converted value per reading, and returns the new array. The parameter is readonly number[], so the checker would reject a push on readings by mistake. The last two lines show that fahrenheit still holds the original values. The array literal [32, 212, ...] is a plain number[], and passing it to a readonly parameter is allowed. (-40 is the one temperature that is the same on both scales.)

Reread 8.8 Pure Functions and Changing Arguments if your result differed.

Question 19 · Short answer

Greeting builder. Write greet(name, greeting = "Hello") with a typed, optional third parameter for the punctuation at the end, which should be "!" when it is left out. Call it with one, two, and three arguments, and once with undefined in the middle.

Check your reasoning

One possible solution:

greet.ts
/**
 * Builds a greeting line.
 *
 * @param name who to greet
 * @param greeting the opening words; "Hello" if not given
 * @param punctuation what to end with; "!" if not given
 */
function greet(name: string, greeting = "Hello", punctuation?: string): string {
  const ending = punctuation === undefined ? "!" : punctuation;
  return `${greeting}, ${name}${ending}`;
}

console.log(greet("Ana"));
console.log(greet("Ben", "Good evening"));
console.log(greet("Chi", "Hey", "?"));
console.log(greet("Dev", undefined, "."));
Hello, Ana!
Good evening, Ben!
Hey, Chi?
Hello, Dev.

Line 8’s header has all three kinds of parameter: name is required, greeting has a default, and punctuation? is optional, in that order, as 8.4 requires. Because punctuation holds undefined when left out, line 9 checks for that and picks "!" with the conditional operator; the checker knows that in the other branch punctuation is a string. The last call passes undefined for greeting to reach the third parameter, so the default "Hello" is used with a full stop. You could also write punctuation = "!" as a second default, which makes the check unnecessary; the exercise asked for an optional parameter so that you handle undefined yourself.

Reread 8.4 Optional Parameters and Default Values if your result differed.

Wrap-up · 6 of 8

Review questions

Question 20 · Tracing

Predict exactly what this program shows. Work out what low and high hold in each call.

review-clamp.ts
let calls = 0;

function clamp(value: number, low = 0, high = 100): number {
  calls++;
  if (value < low) {
    return low;
  }
  if (value > high) {
    return high;
  }
  return value;
}

console.log(clamp(150));
console.log(clamp(-5, -10));
console.log(clamp(7, 0, 5));
console.log(calls);
Check your reasoning
100
-5
5
3
Line value low high Guard that returns Result
14 150 0 100 value > high 100
15 -5 -10 100 neither -5
16 7 0 5 value > high 5

Each call runs line 4 first, so the outer calls goes up by one per call, and line 17 shows 3; clamp is not pure, because of that line. On line 15, -5 is not below the given low of -10, so the value itself comes back.

Reread 8.4 Optional Parameters and Default Values and 8.7 Return Early Instead of Nesting if any line differed.

Question 21 · Multiple choice

format is declared as function format(amount: number, currency = "USD", note?: string): string. Which call does npx tsc accept?

  1. format("5");
  2. format(5, "EUR", "tip", 2);
  3. format(5, undefined, "tip");
  4. format();
Check your reasoning

C. amount gets 5, currency gets undefined and so uses its default "USD", and note gets "tip". Passing undefined is how you skip a middle parameter.

  • A is wrong: "5" is a string, and amount wants a number: TS2345.
  • B is wrong: the function takes 1 to 3 arguments, and this gives 4: TS2554.
  • D is wrong: amount is required, so TS2554, “Expected 1-3 arguments, but got 0.”

Reread 8.4 Optional Parameters and Default Values and 8.1 Declaring and Calling a Function if you chose differently.

Question 22 · Debugging

Priya’s function should label a size as small, medium, or large, and she believes every case is covered. npx tsc rejects it. Predict the message, explain why the checker is right, and rewrite the function with guard clauses.

size-label.ts
function sizeLabel(cm: number): string {
  if (cm < 50) {
    return "small";
  } else if (cm < 100) {
    return "medium";
  } else if (cm >= 100) {
    return "large";
  }
}

console.log(sizeLabel(120));
Check your reasoning
size-label.ts:1:33 - error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

Priya is right that the three conditions cover every number, but the checker does not do algebra: it sees an if chain whose last rung has a condition, cm >= 100, and so the chain may, as far as it can tell, match nothing and fall out of the bottom with no return. Guard clauses fix the shape and the reasoning at once: handle the two smaller sizes and return, then let the last line return "large" for everyone left.

size-label-fixed.ts
function sizeLabel(cm: number): string {
  if (cm < 50) {
    return "small";
  }
  if (cm < 100) {
    return "medium";
  }
  return "large";
}

console.log(sizeLabel(120));
console.log(sizeLabel(49.9));
large
small

The else ifs are gone because each guard returns; the last return needs no condition. If you typed the broken version, fix or delete it before you go on.

Reread 8.7 Return Early Instead of Nesting if you missed it.

Question 23 · Tracing

Predict exactly what this program shows. pop removes an array’s last element, as on Day 6.

review-shared.ts
function tidy(words: string[]): string[] {
  words.pop();
  return words;
}

function trimmed(words: readonly string[]): string[] {
  const copy = [...words];
  copy.pop();
  return copy;
}

const a = ["x", "y", "z"];
const b = tidy(a);
console.log(a.length, b.length);

const c = ["x", "y", "z"];
const d = trimmed(c);
console.log(c.length, d.length);
Check your reasoning
2 2
3 2
  • Lines 12 to 14: tidy pops from the array it was given, which is the same array as a, and then returns that same array. So a and b are two names for one array of length 2: 2 2.
  • Lines 16 to 18: trimmed copies first with [...words], pops from the copy, and returns the copy. c still has 3 elements and d has 2: 3 2.

trimmed is the pure version, and its readonly parameter is what stops anyone from accidentally writing words.pop() inside it.

Reread 8.8 Pure Functions and Changing Arguments if any line differed.

Question 24 · Debugging

npx tsc accepts this program, yet node stops with an error before showing anything. Predict the error, explain why the checker did not catch it, and fix the program.

review-order.ts
console.log(label(3));

function label(n: number): string {
  return `#${pad(n)}`;
}

const pad = (n: number): string => String(n).padStart(3, "0");

console.log(label(42));
Check your reasoning
ReferenceError: Cannot access 'pad' before initialization

Line 1 calls label, which is a declaration, so calling it from above is fine. But label uses pad on line 4, and pad is a const that gets its value on line 7, which has not run yet when line 1 calls. Node stops at line 4 with a runtime error. The checker allows it because, reading line 4 on its own, pad is declared in the outer scope and the body is correct; it cannot tell at which moment the function will be called. The fix is the rule from 8.6: a const must get its value before it is used, so put the calls after it.

review-order-fixed.ts
function label(n: number): string {
  return `#${pad(n)}`;
}

const pad = (n: number): string => String(n).padStart(3, "0");

console.log(label(3));
console.log(label(42));
#003
#042

This is why this course keeps declarations and helpers at the top of a file and the calls at the bottom. If you typed the broken version, fix or delete it before you go on.

Reread 8.6 Arrow Functions if you missed it.

Question 25 · Short answer

A teammate asks: “Why not make every parameter optional with ?, so callers can leave out whatever they like?” Explain what happens inside the function when an optional parameter is left out, why the checker then rejects price * quantity, and when a default value is the better choice.

Check your reasoning

Model answer: An optional parameter that the caller leaves out holds undefined, so inside the function it might be a number or might be undefined. The checker refuses to do arithmetic with a value that might be undefined (TS18048, “possibly undefined”), because undefined * 3 makes no sense, so every use must first check === undefined. That is worth it only when “nothing was given” needs its own behaviour, such as a missing subtitle. When there is a sensible stand-in value, a default (quantity = 1) is better: the caller may still leave the argument out, but inside the function the parameter is always a number and needs no check. And a parameter that the function cannot do its job without should stay required, so that the checker reports a forgotten argument with TS2554 instead of letting undefined in.

A complete answer must:

  • say that a left-out optional parameter holds undefined inside the function,
  • explain that arithmetic on a possibly-undefined value is rejected until it is checked, and
  • say that a default keeps the parameter a plain number, and that required parameters let the checker catch a missing argument.

Reread 8.4 Optional Parameters and Default Values if your reasoning differed.

Wrap-up · 7 of 8

Go further

The Handbook’s chapter on functions covers today’s ideas with more examples; read it up to the “Function Type Expressions” heading, which is where Day 10 starts: TypeScript Handbook: More on Functions. MDN’s guide explains the JavaScript side, including scope and the difference between declarations and expressions: MDN: Functions.

Wrap-up · 8 of 8

Reflection

Check each statement. If the answer is “not yet,” reread the linked subsection.

  • I can declare a function with typed parameters, call it with arguments, and say in what order the lines run. Reread
  • I can return a value with a return type the checker holds me to, and use the call in an expression. Reread
  • I can say when a function should be void, and what a function gives back when it forgets to return. Reread
  • I can choose between a required, default, and optional parameter, and put them in the right order. Reread
  • I can explain which names a function can see, and why a local is gone after the call. Reread
  • I can write a short arrow function and say when it may be called. Reread
  • I can replace nested if and else with guard clauses that return early. Reread
  • I can predict whether a function changes the caller's value, and write the pure version instead. Reread
  • I can write a doc comment with @param and @returns that the editor shows on hover. Reread