Chapter 2 · Decide, repeat, reuse
Functions
Step 1 of 22 · Concept
A function names a piece of work
By the end of this lesson you write functions of your own and know what each call does in memory.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Ada");
functionmakes a function namedgreet. Its body, the block in braces, runs only when it is called.nameis a parameter: a box for a value each call gives.- The call
greet("Ada");runs the body withnameset to"Ada", the argument.
Step 2 of 22 · Quiz
What will it print?
Type what this program prints.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Ada");
greet("Alan");
Step 3 of 22 · Demo
See it run
Run it and compare with your answer: one function, two calls. Then add a third call, greet("Grace");, and run it
again.
Step 4 of 22 · Concept
return sends a value back
function square(n) {
return n * n;
}
const area = square(4);
console.log(area);
returnends the call and sends a value back. The call is replaced by that value:square(4)gives16, andareagets it.- A function without
returngivesundefined.
Step 5 of 22 · Quiz
No return, no value
What does this program print?
function double(x) {
x * 2;
}
function triple(x) {
return
x * 3;
}
console.log(double(4), triple(4));
Step 6 of 22 · Demo
See it run
Run it and compare with your answer.
Then fix both functions: put return before x * 2, and join x * 3; to the return line. Run it again: 8 12.
Step 7 of 22 · Try it
Try it: return, not log
Run it: 12, then Area: undefined. area logs the area itself and sends nothing back.
Make area return w * h in place of logging it. The program must print:
Area: 12
Change console.log(w * h); to return w * h;. The call area(3, 4) then gives 12, and the last line logs it.
Step 8 of 22 · Exercise
Your turn: a grade function
Write grade(score). It returns "A" from 90, "B" from 70, "C" from 50, and "F" under 50. The program
must print:
95 A
72 B
55 C
40 F
Return the letter; do not log it inside grade. A console.log("A") there prints A on its own line, and the call still gives undefined.
Lesson 6's chain: if (score >= 90), then else if (score >= 70), else if (score >= 50) and else. Each block returns its letter.
if (score >= 90) {
return "A";
} else if (score >= 70) {
Step 9 of 22 · Concept
Each call gets a frame
function addOne(n) {
n = n + 1;
}
let x = 5;
addOne(x);
- Each call gets a frame on the stack (lesson 2), with its parameters and variables as boxes. When the call returns, its frame is gone.
- An argument is copied into its parameter:
ngets a copy of what is inx, 5.n = n + 1changes the copy, soxstays 5.
Step 10 of 22 · Trace
Watch a call
Watch square's frame come and go, and its value go back. Press Next to run one moment at a time.
function square(n) {
const result = n * n;
return result;
}
const area = square(4);
console.log(area);- Lines 1–4 only made the function. Line 6 is next: it calls
square(4). square's frame is on top. Its boxnholds 4, a copy of the argument. Line 2 is next.resultis 16. Line 3 is next: it returnsresult.square's frame is gone. Its 16 went intoarea, in the module's frame. Line 7 is next.- Line 7 logged
16. The program is finished.
Step 11 of 22 · Quiz
Which x?
What does this program print?
function addOne(n) {
n = n + 1;
}
let x = 5;
addOne(x);
console.log(x);
Step 12 of 22 · Demo
See it run
Run it and compare with your answer.
To change x, the function must send the new value back. End addOne with return n; and change the call to
x = addOne(x);. Run it again: 6.
Step 13 of 22 · Concept
Variables live inside their braces
const rate = 2;
function pay(hours) {
const total = hours * rate;
return total;
}
console.log(pay(10));
console.log(total);
A box made with let or const lives inside its braces {}: a function's, an if's or a loop's. A for
header's let i belongs to its loop too.
| box | made | seen |
|---|---|---|
rate | outside every {}, in the module's frame | in the whole file, pay too |
hours, total | in pay's frame | only inside pay |
So pay(10) reads rate and logs 20. The last line stops with ReferenceError: total is not defined, read as in
lesson 5.
Step 14 of 22 · Exercise
Your turn: Celsius to Fahrenheit
Write toFahrenheit(c), which returns the temperature in Fahrenheit, c * 9 / 5 + 32. Then log 0, 25, 100 and
-40 degrees with it. The program must print:
0 C is 32 F
25 C is 77 F
100 C is 212 F
-40 C is -40 F
Without return, every line ends in undefined F: the call gives undefined. Return the value from the function, and log it outside.
A function toFahrenheit(c) with one return line. Then one console.log per temperature, with four values: the degrees, "C is", the call and "F".
console.log(25, "C is", toFahrenheit(25), "F");
Step 15 of 22 · Concept
A missing argument is undefined
function area(w, h) {
return w * h;
}
| call | gives | why |
|---|---|---|
area(3, 4) | 12 | w is 3, h is 4 |
area(3) | NaN | h is undefined, and 3 * undefined is NaN |
area(3, 4, 5) | 12 | the extra argument is ignored |
None of these is an error: a missing argument is undefined.
A default value fills a missing argument. function greet(name, times = 2) gives times the value 2 when a call
leaves it out, as greet("Ada") does.
Step 16 of 22 · Quiz
Predict the missing argument
area has two parameters. The second call gives it one argument. Type the missing line.
function area(w, h) {
return w * h;
}
console.log(area(3, 4));
console.log(area(3));
Step 17 of 22 · Demo
See it run
Run it and compare with your answer.
Then give h a default value: function area(w, h = 1) {. Run it again: 12 and 3.
Step 18 of 22 · Concept
An arrow is a shorter function
An arrow function is a shorter function.
(x) => x * 2takesxand returnsx * 2, with noreturn.- With a block in braces after
=>, it needsreturn, as afunctiondoes. - A function is a value:
constnames it, and you can pass it to another function. - A
functiondeclaration is ready from the file's start; aconstfunction only after its line.
Step 19 of 22 · Demo
Functions are values
Run it. greet() runs before its line: a function declaration is ready from the start. applyTwice(double, 3)
passes double itself and calls it twice: 12.
Then move hello(); to the first line and run it: ReferenceError: Cannot access 'hello' before initialization. A
const is ready only after its line.
Step 20 of 22 · Check yourself
Check yourself: ticket prices
No shape this time.
- Write
price(age, day = "weekday"). It returns 5 under age 12, else 8; and 2 more on a"weekend"day. - Write an arrow function
label(name, cost)that returns`${name}: ${cost}`. - Log three tickets. Ada is 10 and comes on a weekday: leave the day out. Alan is 40 and Grace 8; both come on the weekend.
The output must be:
Ada: 5
Alan: 10
Grace: 7
In price, keep the answer in a box made with let. Two separate ifs change it, one for the age and one for the day; then return the box.
Step 21 of 22 · Challenge · optional
Challenge: is it prime?
Optional.
A prime is a whole number over 1 that no number divides but 1 and itself. Write isPrime(n): it returns false
as soon as a number from 2 to n - 1 divides n, else true. Then the loop logs the primes under 20:
2
3
5
7
11
13
17
19
return ends the whole call at once, even from inside a loop. So the first number that divides n can answer false right there.
In isPrime, a for loop with i from 2 while i < n. Inside it, when n % i === 0, return false. After the loop no number divided n: return true.
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
Step 22 of 22 · Recap
Recap
function name(params) { ... }makes a function; a call runs its body.returnsends a value back. Without it, a call givesundefined.- Each call gets a frame. An argument is copied in; a missing one is
undefined. letandconstlive inside their braces; a function reads the names around it.(x) => x * 2is an arrow function. Functions are values: name them, pass them.
Next: lesson 8 splits a program into files and reads its input.
Review
4 questions from this lesson, in a new order each time. Answer from memory: 3 of 4 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Ada");
greet("Alan");
function double(x) {
x * 2;
}
function triple(x) {
return
x * 3;
}
console.log(double(4), triple(4));
function area(w, h) {
console.log(w * h);
}
console.log("Area:", area(3, 4));
function grade(score) {
// return "A", "B", "C" or "F"
}
console.log(95, grade(95));
console.log(72, grade(72));
console.log(55, grade(55));
console.log(40, grade(40));
function addOne(n) {
n = n + 1;
}
let x = 5;
addOne(x);
console.log(x);
// toFahrenheit(c) returns c * 9 / 5 + 32
// log 0, 25, 100 and -40 as: 0 C is 32 F
function area(w, h) {
return w * h;
}
console.log(area(3, 4));
console.log(area(3));
greet();
function greet() {
console.log("Hello from greet");
}
const hello = () => {
console.log("Hello from hello");
};
hello();
const double = (x) => x * 2;
const add = (a, b) => {
return a + b;
};
function applyTwice(f, x) {
return f(f(x));
}
console.log(add(2, 3), applyTwice(double, 3));
// 1. price(age, day = "weekday")
// 2. an arrow function label(name, cost)
// 3. log three tickets
function isPrime(n) {
// false if a number from 2 to n - 1 divides n
}
for (let n = 2; n < 20; n++) {
if (isPrime(n)) {
console.log(n);
}
}