Deciding and repeating
By the end of this lesson you will have changes.js, a loop you wrote by hand that turns a list of closes into daily percentage changes — and the NaN it produces when it starts one step too early.
Two more shapes and you can read most of a real file.
Deciding
let label;
if (change > 0) {
label = "up";
} else if (change < 0) {
label = "down";
} else {
label = "flat";
}
Read top to bottom; the first true branch wins and the rest are skipped. Notice the third branch exists at all — change === 0 is a real case, and forgetting it is how a flat day gets labelled "down".
The comparison to be careful with
"5" == 5 // true — converts, then compares
"5" === 5 // false — compares type as well
Always use ===. The converting version is a source of bugs that look like magic, and every style guide you will meet forbids it.
Repeating
for (const bar of bars) {
console.log(bar.close);
}
For each bar in bars. That is the loop you will use most.
When you need the position too:
for (let i = 1; i < bars.length; i++) {
const change = bars[i].close / bars[i - 1].close - 1;
}
Read the three parts inside the brackets after for as: start with i = 1; keep going while i < bars.length; after each pass add one (i++ means "add one to i"). Look at i = 1, not 0. This loop compares each bar to the one before, so there is nothing to compare the first one to. Starting at zero would reach bars[-1], which is undefined — and undefined.close does not quietly give you a wrong number, it stops the program: TypeError: Cannot read properties of undefined (reading 'close').
The quieter version of the same mistake is worth seeing too. If the list holds bare numbers rather than objects, closes[0] / closes[-1] - 1 produces NaN — a number that is not a number, which spreads silently through every calculation downstream instead of stopping anything. Loud failure is the lucky case.
That exact off-by-one is Backtest Strategies's opening bug. You have now met it before it matters.
Truthiness, and why 0 bites
if (volume) { ... } // false when volume is 0
Empty string, 0, null and undefined are all treated as false. So a legitimate zero — a day with no trades — is skipped by a check meant to test "did we get a value". Write if (volume !== undefined) when that is what you mean.
Try it now
Write the loop that turns a list of closes into a list of daily percentage changes, by hand, in a file called changes.js. Start from const closes = [100, 102, 99.96];, make an empty list with const changes = [];, and add each result to it with changes.push(value). Round each change to two decimals with .toFixed(2) (a number's toFixed(2) gives the text with two decimals, such as "2.00"), because a computer stores most decimals approximately and an unrounded 2 percent prints as 2.0000000000000018. Print the list at the end.
The prompt
Write and run the loop yourself, then paste it into your chat assistant:
I wrote this loop by hand. Do not rewrite it. Walk through it one pass
at a time and tell me what it prints for the closes in the file. Then
tell me what the first result would be if the loop started at i = 0,
and why, without changing my code.
[paste changes.js]
A good answer goes through the loop pass by pass, and says that a first pass at i = 0 divides by closes[-1], which is undefined.
Check it yourself
- With the closes
[100, 102, 99.96], the loop gives back two changes,2.00and-2.00: one fewer than the closes, as the first day has no yesterday. - Inside the loop, right after the line that computes
change, paste the up/down/flatiffrom "Deciding" above and print the label beside the change:console.log(change.toFixed(2), label);. Then add99.96once more at the end of your closes, so two days in a row close the same. That day prints0.00 flat. - Every comparison in your file uses
===, never==.
Break it on purpose
Deliberately start it at i = 0 and look at what the first result is. NaN propagating through a calculation is worth seeing once, early, on lines you wrote yourself. With the labels in, that first line reads NaN flat: NaN is neither above nor below zero, so the last branch catches it. An else catches everything the branches above it did not, not only the case you had in mind.
Compare with ours
Our changes.js, with the labels from step 2
const closes = [100, 102, 99.96, 99.96];
const changes = [];
for (let i = 1; i < closes.length; i++) {
const change = (closes[i] / closes[i - 1] - 1) * 100;
let label;
if (change > 0) {
label = "up";
} else if (change < 0) {
label = "down";
} else {
label = "flat";
}
console.log(change.toFixed(2), label);
changes.push(change.toFixed(2));
}
console.log(changes);
It prints 2.00 up, -2.00 down, 0.00 flat, then [ '2.00', '-2.00', '0.00' ]. Without toFixed(2) the first change prints as 2.0000000000000018. A computer stores most decimals approximately; two places are what a percentage needs, and the tail is noise.
Checkpoint
git status # only the files you expect, and no .env*
git add -A
git commit -m "Daily changes from closes, starting at 1: the first day has no yesterday"
Then answer this lesson's questions.