At some point in any program (as in life) you have to face a choice.

This is an essential part of programming.

Did the user type a number or a letter? Was it the number 1 or a number bigger than 5? Is this an image or a PDF file?

We call those conditionals. There is code that will only run if a condition is satisfied. Other code will not even run, if a condition is not met.

We wrap those portion of codes into blocks. In JavaScript, blocks are identified by parentheses.

The most common conditional is if. Available in most languages under this name, it verifies a condition before running the code contained in its block:

if (2 > 1) {
  //run this code
}

This is a simple example that always executes. Because 2 is bigger than 1. Usually you compare variables:

if (a > b) {
  //run this code
}

After an if statement you can link an else statement, to execute code if the if condition is not met:

if (a > b) {
  //run this code
} else {
  //run this other code
}

Those blocks can be nested, to create more complex scenarios:

if (a > b) {
  if (c > 5) {
    //run this code
  } else {
    //run this other code
  }
} else {
  //run this other code
}

Another conditional statement in JavaScript is switch. Compared to if, it allows for an easier definition of multiple choices:

switch (a) {
  case 1:
    //do something
    break
  case 2:
    //do something
    break
  case 3:
    //do something
    break
}

I mention JavaScript to give you the real syntax that you’re going to use, but those are all general constructs that you will find in many different languages, maybe slightly changed but more or less equivalent.

Another conditional in JavaScript is the ternary operator ?: which allows a more terse syntax:

isTrue ? /* do this */ : /* do that */

We’ll learn more about this, and the other conditionals, in the JavaScript Fundamentals course.


Go to the next lesson