Conditions and Loops

Conditions provide a simple but powerful way to control the flow of execution through a piece of code. Loops allow you to perform repeating operations with less code. Let's take a look at:

  • if conditions,
  • switch statements,
  • while, do-while, for, and for-in loops.

Code Blocks

Let's start by clarifying what a block of code is, as blocks are used extensively when constructing conditions and loops.

A block of code consists of zero or more expressions enclosed in curly brackets.

{
  var a = 1; 
  var b = 3;
}

You can nest blocks within each other indefinitely:

{
  var a = 1; 
  var b = 3;
  var c, d;
  {
    c = a + b;
    {
      d = a - b;
    }
  }
}

Tip

Best Practice Tips

  • Use end-of-line semicolons. Although the semicolon is optional when you have one expression per ...

Get Object-Oriented JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.