Functions for Game Actions
Package game actions like jumping, scoring and resetting into functions, pass in values with parameters and get answers back with return.
Welcome back!
Step 1 of 11Learn
Naming a chunk of code
As games grow, the same actions happen in many places. The player loses a life when hit by an enemy, when falling off a ledge and when the timer runs out. Copying the "lose a life" code three times means three places to fix when you change it. A function gives a chunk of code a name so you can run it from anywhere:
function loseLife() {
lives--;
if (lives <= 0) {
isGameOver = true;
}
}Defining a function doesn't run it. It just teaches JavaScript a new command. To run it, you call it by name with parentheses:
loseLife();Now every hazard in the game calls loseLife(), and if you later add a "shield absorbs one hit" rule, you add it in one place.
Good function names are verbs that describe the action: jump, spawnEnemy, resetLevel, drawPlayer. If you struggle to name a function, it's often doing too many things and should be split into two.
Step 2 of 11Note
Step 3 of 11Practice · True or false
Writing function jump() { ... } in your code makes the player jump as soon as the page loads.
Step 4 of 11Learn
Parameters and return values
Functions get far more useful when they take inputs and give back outputs.
Parameters are input names listed in the parentheses. The values you pass in when calling are called arguments:
function addPoints(amount) {
score += amount;
}
addPoints(10); // a coin
addPoints(250); // a bossReturn values send a result back to whoever called the function:
function pointsFor(enemyType) {
if (enemyType === "boss") {
return 250;
}
return 10;
}
score += pointsFor("boss");When JavaScript reaches return, the function stops immediately and the value replaces the call. So pointsFor("boss") becomes 250, and the line becomes score += 250.
The best functions often work like a calculator: values in, answer out, nothing else changed. They're called pure functions, and they're easy to test because the same inputs always give the same answer. That's exactly why every code challenge in this course asks you to write functions that return values.
Step 5 of 11Diagram
What happens in score += pointsFor("boss")
Tap a shape with to see more.
- Argument "boss"
The value you pass in the call.
- Parameter enemyType
Inside the function,
enemyTypenow holds"boss".- Body checks the type
if (enemyType === "boss") return 250;- return 250
returnstops the function and sends 250 back.- score += 250
The call is replaced by the returned value.
Step 6 of 11Practice · Match the pairs
In the code function area(w, h) { return w * h; } let a = area(4, 5);, match each piece to its role.
Tap an answer, then tap the place where it belongs (or drag it there).
- area
- w and h
- 4 and 5
- w * h
- a
Step 7 of 11Learn
Return versus console.log
Beginners often mix up returning a value and printing it. Compare:
function doubleA(n) { console.log(n * 2); }
function doubleB(n) { return n * 2; }doubleA(5) shows 10 in the console, but the function gives nothing back. Its result is undefined, so score += doubleA(5) would turn your score into NaN (Not a Number), a famous source of broken scoreboards.
doubleB(5) hands 10 back to the code, where it can be stored, compared or added. Printing is for you, the developer, while debugging. Returning is for the program.
One more detail: variables created with let inside a function exist only inside that function. This is called scope:
function test() {
let secret = 42;
}
console.log(secret); // error: secret is not definedScope is helpful. A variable named speed inside moveEnemy won't clash with a speed inside movePlayer. Game state that many functions share, like the score, lives at the top of the file instead.
Step 8 of 11Compare
console.log vs. return
| Aspect | console.log(n * 2) | return n * 2 |
|---|---|---|
| Who it is for | You, the developer | The program |
| Value of the call | undefined | The number, e.g. 10 |
| score += double(5) | score becomes NaN | score goes up by 10 |
| Use it for | Debugging | Results you store, compare or add |
Step 9 of 11Note
Step 10 of 11Practice · Code challenge
Write damage(health, hit, hasShield) that returns the player's new health. A shield halves the hit (so a hit of 30 does 15). Health can never go below 0.
damage(100, 30, false)damage(100, 30, true)damage(20, 50, false)damage(10, 40, true)
Step 11 of 11Practice · Choose one
A function is written as function bonus(x) { console.log(x * 3); }. What is the value of score after let score = 10; score = score + bonus(2);?
Lesson complete!