Blocks
The phone store employee must go through a series of steps to complete the checkout as you buy your new phone.
Similarly, in code we often need to group a series of statements together, which we often call a block. In JavaScript, a block is defined by wrapping one or more statements inside a curly-brace pair { .. }
. Consider:
var amount = 99.99;
// a general block
{
amount = amount * 2;
console.log( amount ); // 199.98
}
This kind of standalone { .. }
general block is valid, but isn’t as commonly seen in JS programs. Typically, blocks are attached to some other control statement, such as an if
statement (see “Conditionals”) or a loop (see “Loops”). For example:
var amount = 99.99;
// is amount big enough?
if (amount > 10) { // <-- block attached to `if`
amount = amount * 2;
console.log( amount ); // 199.98
}
We’ll explain if
statements in the next section, but as you can see, the { .. }
block with its two statements is attached to if (amount > 10)
; the statements inside the block will only be processed if the conditional passes.
Note: Unlike most other statements like console.log(amount);
, a block statement does not need a semicolon (;
) to conclude it.