Essential JavaScript

Blocks

One way to organize our code is to use blocks.

A block statement is a way to group other statements together.

We have already used block statements while working with if statements:

var x = 2;
if (x < 4) {
  x++;
}

The truth is, those curly braces and everything in between them are a single JavaScript statement!

Why Blocks?

An if statement only applies to a single statement. We could have written the above example this way:

var x = 2;
if (x < 4) x++;

However, the curly braces of a block statement are widely considered easier to read, even if they involve more lines.

Besides, if we need to execute two or more statements together, we need to use a block statement to group them anyway:

var x = 2;
var y = 4;
if (x < y) {
  x++;
  y--;
}

Using block statements with if, else if, else, and similar statements is a best practice.

Arbitrary Blocks

We can also create arbitrary blocks of code without any if, else if, or else statement:

var x = 2;
var y = 4;
{
  x++;
  y--;
}

Without a conditional statement in front of it, the block statement will always run.

Next, we will learn how to use block statements to keep our variables organized.


Learning Goals

Code Editor