‹ Start From Zero Lesson 6 of 21
Contents Lesson 6 of 21

4 min read · foundations

Functions — a box that takes something and gives something back

Most code you read will be functions. Learn to read one and most of a file stops being mysterious.

The shape

function percentChange(from, to) {
  return (to / from - 1) * 100;
}

percentChange(100, 110);   // 10

A name, some inputs, and a return. Reading one is three questions: what goes in, what comes out, and does it touch anything outside itself?

That third question is the one beginners skip and the one that matters when reviewing generated code.

Two ways to write the same thing

const percentChange = (from, to) => (to / from - 1) * 100;

An arrow function. Shorter, extremely common, and when the body is a single expression the return is implied. You need to read both forms; write whichever you prefer.

A function that returns nothing

function show(price) {
  console.log(price);
}

No return, so calling it gives you undefined. It was called for its effect, not its value. Both kinds exist and the distinction is worth noticing while reading: a function whose value you ignore should be doing something, and a function that does something and returns a value is often doing too much.

Pure is easier to trust

percentChange uses only its inputs and changes nothing else. Give it the same numbers and it gives the same answer, forever. That property is called pure, and it is why course 3 can test a strategy's signal function with fixed fixtures and no network at all.

A function that reads the clock, or the network, or a global, is not pure — and each of those is a reason it might behave differently tomorrow.

Small enough to hold

If you cannot say what a function does in one sentence, it is doing more than one thing. Splitting it is not tidiness; it is what makes the pieces testable and reviewable.

Try it now

Write three by hand, no assistant: one that formats a number as a percentage to two decimals, one that returns the larger of two numbers, and one that takes a ticker and returns it uppercased. Then, for each, answer the three reading questions out loud. That habit is what unit 2 of course 1 is built on.