Functions Working Together

Grade 6, page 8 of 11. A one-minute read.

Functions really shine when you combine them. Big problems become a collection of small, easy problems, each solved by its own function:

JavaScript
const TAX_RATE = 0.15;

function calculateSubtotal(price, quantity) {
  return price * quantity;
}

function calculateTax(amount) {
  return amount * TAX_RATE;
}

function formatMoney(amount) {
  return `$${amount.toFixed(2)}`;
}

function printReceipt(item, price, quantity) {
  const subtotal = calculateSubtotal(price, quantity);
  const tax = calculateTax(subtotal);
  const total = subtotal + tax;

  console.log(`${quantity} x ${item}`);
  console.log(`Subtotal: ${formatMoney(subtotal)}`);
  console.log(`Tax:      ${formatMoney(tax)}`);
  console.log(`Total:    ${formatMoney(total)}`);
}

printReceipt("Notebook", 12.5, 4);

It prints

4 x Notebook
Subtotal: $50.00
Tax:      $7.50
Total:    $57.50

Look at how readable printReceipt is. It almost reads like English: calculate the subtotal, calculate the tax, add them up, print it all out. Each little function does one small job, and does it well. If the tax rate changes, we change one line. If we want a different money format, we change one function.

Passing functions to functions

Since functions are values, you can even pass a function into another function as an argument:

JavaScript
function doTwice(action) {
  action();
  action();
}

function cheer() {
  console.log("Hip hip hooray! 🎉");
}

doTwice(cheer);
doTwice(() => console.log("Clap! 👏"));

It prints

Hip hip hooray! 🎉
Hip hip hooray! 🎉
Clap! 👏
Clap! 👏

Notice that we wrote doTwice(cheer), not doTwice(cheer()). We're handing over the function itself (the recipe card), so that doTwice can call it whenever it wants. If we wrote cheer(), we'd be calling it immediately and passing in its result instead.

A function that you pass into another function is called a callback. This idea is everywhere in JavaScript: you'll use callbacks to react to button clicks, to process lists of data, and to wait for things to load from the internet. We'll explore callbacks in depth in Grade 10. For now, just know that functions can be passed around like any other value.

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