Reading Blocks by Their Braces
In this lesson, you found out why the release note’s JavaScript port printed the triage call on a
day with no open bugs, and how to put that line inside the if.
- Python reads a block from its indentation, but JavaScript doesn’t read indentation at all. An
ifwithout braces controls exactly one statement, so the next line runs every time, however it’s indented. - Curly braces make the block: the opening brace after the condition starts it, and the closing
brace ends it. A braced block counts as one statement, so the
ifcontrols all of it. - Always write the braces, even around one line, so a line someone adds under an
iflands inside the block. A formatter then lines each indent up with the braces you wrote.
Here’s the port as the teammate left it, on a day with no open bugs. The second console.log()
line was added today, indented like the one above:
const BUGS_OPENED = 9;
const BUGS_CLOSED = 9;
const openBugs = BUGS_OPENED - BUGS_CLOSED;
console.log(`Open bugs: ${openBugs}`);
if (openBugs > 0)
console.log("Please check the bug tracker.");
console.log("Triage call at 9:30 tomorrow.");
It prints the triage line anyway, because that line is the next statement after the if, not
part of it:
Open bugs: 0
Triage call at 9:30 tomorrow.
With braces, both lines belong to the if:
const BUGS_OPENED = 9;
const BUGS_CLOSED = 9;
const openBugs = BUGS_OPENED - BUGS_CLOSED;
console.log(`Open bugs: ${openBugs}`);
if (openBugs > 0) {
console.log("Please check the bug tracker.");
console.log("Triage call at 9:30 tomorrow.");
}
On a day with no open bugs, it prints the same note as the Python script:
Open bugs: 0
The braces decide, whatever the indentation says. If the triage line lost its indent but stayed above the closing brace, it would still be inside the block and still be skipped.
Watch out for typing Python’s header into JavaScript: with no parentheses and a colon at the end,
if openBugs > 0: stops the file with a SyntaxError before anything runs.
Next up: Writing Empty Blocks and Comments, a text lesson, where the script’s else branch
holds only pass and a reminder to do later.