Deciding and repeating
Two more shapes and you can read most of a real file.
Deciding
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;
}
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 course 3'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. Then 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 four lines you wrote yourself.