Javascript · Functions (Advanced)
Functions as Values
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — A Function Is a Value
Since the start of this class, you've seen that a function can be stored in a variable. That works because in JavaScript a function is a value, like a number or a string. `typeof` even has a word for it:
const cheer = () => console.log("Go!");
console.log(typeof cheer);
console.log(typeof 42);
console.log(typeof "Zap");
And like any value, a function can be copied into another variable. Both names then point to the same function:
const cheer = () => console.log("Go Aquachu!");
const shout = cheer;
shout();
cheer();
Exercise 2 — Functions in Arrays
Since a function is a value, an array can hold functions. Here's a list of moves, each one being a function:
const spark = () => console.log("Zap uses Spark!");
const thunder = () => console.log("Zap uses Thunder!");
const moves = [spark, thunder];
moves[0]();
moves[1]();
`moves[0]` is the function, `moves[0]()` calls it. And a loop can run them all:
const spark = () => console.log("Zap uses Spark!");
const thunder = () => console.log("Zap uses Thunder!");
const moves = [spark, thunder];
for (let move of moves) {
move();
}
Exercise 3 — Quiz: typeof a Function
What does this code print?
const heal = (hp) => hp + 10;
console.log(typeof heal);
Options
• ```"function"```
• ```"object"```
• ```"number"```
• ```undefined```
Hint : Functions have their own answer from typeof.
Exercise 4 — Run Them All
Put the two functions in the array, then call each one in the loop.
const wave = () => console.log("Wave!");
const tide = () => console.log("Tide!");
const moves = [____, ____];
for (let move of moves) {
move____;
}
Options: wave tide () "wave" wave() []
Hint : Store the functions themselves, without quotes or parentheses, then call the loop variable.
Exercise 5 — Passing a Function to a Function
Since a function is a value, it can also be passed as an argument to another function. The receiving function gets it as a parameter and can call it whenever it wants:
function repeatTwice(action) {
action();
action();
}
const cheer = () => console.log("Go Zap!");
repeatTwice(cheer);
Note the call: `repeatTwice(cheer)`, without parentheses after `cheer`. You pass the function itself, not its result. Inside, `action` is just another name for `cheer`.
Exercise 6 — Quiz: With or Without Parentheses
You want to give the `cheer` function to `repeatTwice` so it can run it. Which call is right?
Options
• ```repeatTwice(cheer);```
• ```repeatTwice(cheer());```
• ```repeatTwice("cheer");```
• ```repeatTwice(cheer)();```
Hint : Parentheses would run the function immediately and pass its result instead.
Exercise 7 — Choosing a Function at Runtime
Because functions are values, you can pick one with a condition and store the choice. The code that calls it doesn't need to know which one was chosen:
const splash = (target) => target + " is soaked!";
const burn = (target) => target + " is burning!";
let type = "fire";
let attack;
if (type === "water") {
attack = splash;
} else {
attack = burn;
}
console.log(attack("Florachu"));
Change `type` to `"water"` and run again: same call, different behaviour.
Exercise 8 — Pass It Along
Complete `runThreeTimes` so it calls the received function three times, then pass `train` to it.
function runThreeTimes(action) {
for (let i = 0; i < 3; i++) {
____();
}
}
const train = () => console.log("Training...");
runThreeTimes(____);
Options: action train train() "train" i
Hint : Inside, use the parameter name. Outside, pass the function without calling it.
Exercise 9 — Function or Result?
`cheer` is a function. Match each expression with what it is.
Items to match
• cheer
• cheer()
• const c = cheer;
Definitions
• The function itself
• The result of running it
• A second name for the same function
Exercise 10 — Move Selector
Zap knows three moves, each one a function that receives a target and returns a message. Build a small system around them.
Step 1: create a constant `moves` holding the three functions in order: spark, thunder, charge.
Step 2: write `useMove(index, target)` that takes the function at that index in `moves`, calls it with the target, and prints the result.
Step 3: write `useAll(target)` that runs every move on the target, in order.
Step 4: call `useMove(1, "Florachu")`, then `useAll("Rockachu")`.
Thunder hits Florachu!
Spark hits Rockachu!
Thunder hits Rockachu!
Charge hits Rockachu!
Starter code
const spark = (target) => "Spark hits " + target + "!";
const thunder = (target) => "Thunder hits " + target + "!";
const charge = (target) => "Charge hits " + target + "!";
// Write your code here
Back to the course