Javascript · Functions (Advanced)
Anonymous Functions
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — No Name Needed
In the last chapter, every callback was stored in a variable first. But if a function is used once, right where it's passed, why give it a name? You can write it inline:
// With a named variable const cheer = () => console.log("Go!"); repeat(3, cheer); // Anonymous: the function is written right in the call repeat(3, () => console.log("Go!"));
function repeat(times, action) { for (let i = 0; i < times; i++) { action(); } } repeat(3, () => console.log("Go Zap!"));
A function without a name is called an anonymous function. Arrow functions are almost always used this way.
Exercise 2 — Anonymous With Parameters
The inline function can take parameters like any other. Here the callback receives each member:
function forEachMember(team, action) { for (let cdm of team) { action(cdm); } } forEachMember(["Aquachu", "Zap"], (name) => console.log("Hello " + name + "!"));
When the body needs several lines, use braces. It's common to put the closing `});` on its own line:
function forEachMember(team, action) { for (let cdm of team) { action(cdm); } } forEachMember(["Aquachu", "Zap"], (name) => { const shout = name.toUpperCase(); console.log(shout + " joins the fight!"); });
Exercise 3 — Spot the Anonymous Function
Which call passes an anonymous function?
Options
• ```repeat(2, () => console.log("Hi"));```
• ```repeat(2, cheer);```
• ```repeat(2, cheer());```
• ```repeat(2, "cheer");```
Hint : Look for a function written directly inside the parentheses of the call.
Exercise 4 — Inline Callback
Pass an anonymous arrow function that prints `Charging...` to `repeat`.
function repeat(times, action) { for (let i = 0; i < times; i++) { action(); } } repeat(2, ____ ____ console.log("Charging..."));
Options: () => function {} ->
Hint : No parameters, then the arrow, then the single expression.
Exercise 5 — Named or Anonymous?
Both are fine. Choose based on reuse and readability:
const isElectric = (move) => move === "Spark" || move === "Thunder"; function countIf(values, test) { let count = 0; for (let v of values) { if (test(v)) { count++; } } return count; } // The name says what we count: clearer than an inline test console.log(countIf(["Spark", "Splash", "Thunder"], isElectric)); // A trivial test can stay inline console.log(countIf([1, 2, 3, 4], (n) => n > 2));
Exercise 6 — Quiz: Inline Result
What does this code print?
function apply(value, transform) { return transform(value); } console.log(apply(5, (n) => n * 3));
Options
• ```15```
• ```5```
• ```n * 3```
• ```undefined```
Hint : The inline function is called with the value, and its result is returned.
Exercise 7 — Inline With a Parameter
Pass an anonymous function that receives a name and prints it followed by ` is ready!`.
function forEachMember(team, action) { for (let cdm of team) { action(cdm); } } forEachMember(["Zap", "Metachu"], (____) ____ console.log(____ + " is ready!"));
Options: name => name cdm function ->
Hint : Declare the parameter, add the arrow, then use that same parameter in the body.
Exercise 8 — Anonymous Cheat Sheet
Match each element with its description.
Items to match
• Anonymous function
• run(() => { })
• const f = () => { }
• Used in several places
Definitions
• A function without a name
• Anonymous callback passed inline
• Anonymous function stored under a name
• Better stored in a named variable
Exercise 9 — Battle Log
A `forEachMember` helper is provided. Use it three times, each time with an anonymous arrow function written inline: no named callback variables allowed.
Step 1: print each name with `"- "` in front. Step 2: print each name in uppercase followed by `" attacks!"`. Step 3: count how many names are longer than 5 characters in a variable `longNames` (the callback can modify it), then print `"Long names: N"`.
Expected output:
- Aquachu - Zap - Metachu AQUACHU attacks! ZAP attacks! METACHU attacks! Long names: 2
Starter code
function forEachMember(team, action) { for (let cdm of team) { action(cdm); } } const team = ["Aquachu", "Zap", "Metachu"]; let longNames = 0; // Write your code here
Back to the course