Small functions
JavaScript · Unit 19: Clean code
- Full plan
- JavaScript
- 8 exercises
A function does one thing. The one that computes, returns; the one that shows, prints.
When it returns, the caller decides what to do with the result: print it, compare it or keep doing math.
function withTip(bill) {
return bill + bill / 10;
}
const payment = withTip(300);
console.log(payment);
console.log(payment / 4);Prints
330 82.5
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Find the bug
addUpshould be usable to keep calculating: the program has to print 170. Which line has the error?3. Multiple choice
You want to use the average to decide whether the class passes. Why doesn't this function work for you?
4. Predict the output
What does this code print?
5. Complete the code
Only members get the 10% discount. Fill in the guard that sends everyone else away.
6. Put the lines in order
Put
ticket(age)in order using guards: 0 for under 4, 50 for under 18 and 100 for everyone else.7. Find the case that fails
average(scores)gives the average of the scores, and 0 if there are none. Which call does it fail on?8. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.