Javascript · Functions (Basics)
Challenge
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — Potion Shop
Sam walks into the potion shop. Potions cost 30 gold each. You'll write two small functions, then use them to handle Sam's purchase.
Step 1: write `price(quantity)`. It receives a number of potions and returns the total cost. For example, `price(2)` returns `60`.
Step 2: write `canAfford(gold, total)`. It receives the gold Sam has and a total to pay, and returns `true` if the gold is enough, `false` otherwise. For example, `canAfford(50, 60)` returns `false`.
Step 3: Sam has `gold` and wants `wanted` potions. Use your two functions to print `"Total: X gold"`, then `"Deal!"` if Sam can pay, or `"Not enough gold"` if not.
Expected output:
Total: 120 gold Not enough gold
Starter code
let gold = 100; let wanted = 4; // Write your functions here // Use them here
Exercise 2 — Team Helpers
You have a team and the level of each member. The two arrays go together: `levels[0]` is the level of `team[0]`, `levels[1]` the level of `team[1]`, and so on. Write three functions that work for any team, not just this one.
Step 1: write `countTeam(team)`. It receives an array and returns how many members it holds. With the team above, it returns `3`.
Step 2: write `listTeam(team)`. It receives an array and prints each member on its own line, with `"- "` in front. It returns nothing.
Step 3: write `strongest(team, levels)`. It receives both arrays and returns the name of the member with the highest level. With the arrays above, it returns `"Pyrochu"`.
Step 4: use the three functions to produce this output:
Members: 3 - Aquachu - Pyrochu - Florachu Strongest: Pyrochu
Starter code
const team = ["Aquachu", "Pyrochu", "Florachu"]; const levels = [8, 14, 11]; // Write your functions here // Use them here
Exercise 3 — Turn Simulator
Pyrochu fights a wild Metachu. Metachu starts with 70 HP and Pyrochu deals 25 damage every turn. You'll write two functions, then a loop that uses them to play the fight.
Step 1: write `hit(hp, damage)`. It receives the current HP and the damage taken, and returns the HP left after the hit. HP can never go below 0: `hit(10, 25)` returns `0`, not `-15`.
Step 2: write `isKO(hp)`. It receives HP and returns `true` if they are at 0, `false` otherwise.
Step 3: write a loop that repeats as long as Metachu is not KO. At each turn: add 1 to `turn`, apply a hit of `damage` to `metachuHP`, then print `"Turn N: Metachu has X HP"`.
Step 4: after the loop, print `"Metachu fell in N turns"`.
Expected output:
Turn 1: Metachu has 45 HP Turn 2: Metachu has 20 HP Turn 3: Metachu has 0 HP Metachu fell in 3 turns
Starter code
let metachuHP = 70; let damage = 25; let turn = 0; // Write your functions here // Write your loop here
Back to the course