Functions — a box that takes something and gives something back
By the end of this lesson you will have three small functions in functions.js, written by hand and each called once, with the three reading questions answered in a comment above each one.
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 Backtest Strategies 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.
Three tools you will need
The exercise below needs three things that JavaScript already has built in. Each is a small function of its own:
(0.5).toFixed(2) // "0.50" a number rounded to 2 decimals, as text
Math.max(3, 7) // 7 the larger of two numbers
"aapl".toUpperCase() // "AAPL" the same text in capitals
Writing a function around one of these is the exercise: the function gives the idea a name and fixes what goes in and what comes out.
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, in a file called functions.js, using the three tools above. Name them formatPercent, larger and upper. formatPercent takes a fraction such as 0.1234 and returns the text "12.34%" (multiply by 100, round to two decimals, add the %); larger returns the larger of two numbers; upper takes a ticker and returns it in capitals. Put each answer to the three questions in a comment above the function, starting a line with //. Then, for each, answer the three reading questions out loud. That habit is what unit 2 of Build Your First Tool is built on.
The prompt
Write the three functions first, with your answers to the reading questions as comments above them. Then paste the file into your chat assistant:
I wrote these three functions by hand and answered three questions
about each in a comment: what goes in, what comes out, and does it
touch anything outside itself. Do not rewrite them. Tell me where my
answers are wrong or incomplete. Then name one input to each function
that gives a wrong or surprising result, and stop there: do not fix
anything.
[paste functions.js]
A good answer agrees that all three touch nothing outside themselves, and finds an input you had not thought of: two equal numbers, a percentage that rounds, a ticker that is not text at all. The prompt stops it short of fixing on purpose: working out why that input breaks your function, and fixing it, is your half of the exercise.
Check it yourself
formatPercent(0.1234)gives back"12.34%", andtypeofsays it is a string.larger(3, 7)andlarger(7, 3)both give back7, and two equal numbers give back that number.upper("aapl")gives back"AAPL".- None of the three prints anything or reads a name defined outside it, so each is pure. The calls and the prints sit at the bottom of the file.
Break it on purpose
Call upper() with nothing between the brackets. The error reads Cannot read properties of undefined (reading 'toUpperCase') — the same shape as the .close error unit 3 shows you, for the same reason: there was nothing there to ask.
Compare with ours
Our functions.js
// in: a fraction such as 0.1234 · out: the text "12.34%" · touches: nothing
const formatPercent = (x) => (x * 100).toFixed(2) + "%";
// in: two numbers · out: the larger one · touches: nothing
const larger = (a, b) => Math.max(a, b);
// in: a ticker · out: the same ticker in capitals · touches: nothing
const upper = (ticker) => ticker.toUpperCase();
console.log(formatPercent(0.1234), larger(3, 7), upper("aapl"));
Yours may use function rather than arrows, or compare the two numbers yourself. What matters is that you can answer the three questions about each.
Checkpoint
git status # only the files you expect, and no .env*
git add -A
git commit -m "Three pure functions, each with what goes in, what comes out and what it touches"
Then answer this lesson's questions.