Conditional Flows

Programs are a set of instructions that are by default executed in the sequence as they are written. However, it is a common requirement that some parts of a program are executed only if certain conditions are met. These are referred to as conditional flows.

Conditions can be chained so that one set of instructions are executed on one set of conditions, the second set of instructions on the second set of conditions, and so on until a final set of instructions that are executed if none of the specified conditions are met. In any conditional flow, some, all, or no instructions may be executed.

There are three commonly used conditional flows:

  • if-else

The if-else flow is the most commonly used. It executes the set of instructions in the if block if the specified condition is met or the set of instructions in the else block if the specified condition is not met.

This is how an if-else statement is written:

let a = 20, b = 10;
 
if(a > b){
  console.log('a is greater than b');
}else{
  console.log('a is not greater than b');
}

if-else blocks can be chained any number of times, with slightly different construct that is written as if-else if-else with only one starting if, one ending else and the else if repeated as many time as required.

This is how a chained if-else statement is written:

let a = 20, b = 10;
 
if(a > b){
  console.log('a is greater than b');
}else if(a < b){
  console.log('a is not greater than b');
}else if(a === b){
  console.log('a is equal to b');
} else{
  console.log('Could not compare the values.') // This will execute if say you initialize b = 'a';
}
  • ?: (Ternary Operator)

The ternary operator is a very concise way to write an if-else statement. The first argument is a comparison statement, the second is the result of a true comparison, and the third is the result of a false comparison.

This is how a ternary operator condition is written:

let a = 20, b = 10;
 
a > b ? console.log('a is greater than b') : console.log('a is not greater than b');
  • switch(){}

The switch statement checks for the value of one variable and executes a set of instructions depending on the value. The list of values that can be compared to must be specified and there can be a default set of instructions if none of the specified values are matched.

This is how a switch statement is written:

let color = 'red';
 
switch (color) {
  case 'red':
    console.log('The color is red.');
    break;
  case 'amber':
    console.log('The color is amber.');
    break;
  case 'green':
    console.log('The color is green.');
    break;
  default:
    console.log('The color is unknown.');
}