Good Function Habits

Grade 6, page 9 of 11. A two-minute read.

Writing a function is easy. Writing a good function takes a bit of practice. Here are the habits that will make your functions a joy to use:

1. Name functions with verbs. Functions do things, so their names should describe the action: calculateTotal, getUserName, sendMessage, drawCircle. For functions that answer a yes/no question, start with is, has or can: isEven, hasPermission, canAfford.

2. Do one thing. Each function should have one clear job. If you find yourself naming a function calculateTotalAndSendEmailAndUpdateScreen, that's three functions pretending to be one.

3. Keep them short. If a function doesn't fit on your screen, it's probably doing too much. Break it into smaller functions.

4. Prefer returning over printing. A function that returns a value is far more flexible than one that prints it. The caller can always decide to print the result, but they can't un-print something.

5. Avoid too many parameters. Three is plenty. If you need more, there's a better way using objects (Grade 8).

Professor’s CornerPure functions

A function is called pure if (1) it always gives the same output for the same inputs, and (2) it doesn't change anything outside itself (no printing, no changing outside variables). add(a, b) is pure: add(2, 3) is always 5, and it doesn't touch anything else. Pure functions are wonderful because they're predictable and easy to test. Anything a function does besides returning a value (like printing, or changing a variable outside the function) is called a side effect. Programs need side effects to be useful (otherwise you'd never see any results!), but it's a good idea to keep most of your functions pure and put the side effects in just a few places.

Professor’s CornerA function that calls itself

A function can even call itself! This is called recursion. It sounds like it would loop forever (and it will, if you're not careful), but with a stopping condition, it's a powerful technique:

JavaScript
function countdown(n) {
  if (n === 0) {
    console.log("Liftoff! 🚀");
    return;
  }
  console.log(n);
  countdown(n - 1);
}

countdown(3);

It prints

3
2
1
Liftoff! 🚀

Each call handles one number, then asks a slightly smaller version of itself to handle the rest. The if (n === 0) part, which stops the recursion, is called the base case. Recursion is an advanced topic, so don't worry if it makes your head spin. Professor Semicolon has been spinning since 1995.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning