Skip to the content

Small functions

JavaScript · Unit 19: Clean code

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. 1. Predict the output

    What does this code print?

  2. 2. Find the bug

    addUp should be usable to keep calculating: the program has to print 170. Which line has the error?

  3. 3. Multiple choice

    You want to use the average to decide whether the class passes. Why doesn't this function work for you?

  4. 4. Predict the output

    What does this code print?

  5. 5. Complete the code

    Only members get the 10% discount. Fill in the guard that sends everyone else away.

  6. 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. 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. 8. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →