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:

  1. var amount = 99.99;
  2. // a general block
  3. {
  4. amount = amount * 2;
  5. console.log( amount ); // 199.98
  6. }

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:

  1. var amount = 99.99;
  2. // is amount big enough?
  3. if (amount > 10) { // <-- block attached to `if`
  4. amount = amount * 2;
  5. console.log( amount ); // 199.98
  6. }

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.