Conditional statements

Conditional statements

What are statements?

JavaScript source code is a set of statements. There are a couple of different statement types. We have already seen one of them, the variable statement:

  1. var myVar = ‘hello ‘ + ‘world’;

We’ve also seen the expression statement:

  1. 3 + 4;
  2.  
  3. // more often like this
  4. var x = (3 + 4);
  5. var y = (5 + x);

A statement closes with a semicolon, but we will see later that missing semicolons are automatically inserted (for readability reasons, we highly recommend systematically adding a semicolon at the end of all statements).

Statements are generally executed sequentially from top to bottom of the script. However, this flow can be modified by statements such as conditional statements and iteration statements.

The block statement

The block statement is a simple statement which allows us to group a set of statements wrapped in curly braces. 

Block statement:

  1. {
  2.     var i = 0;
  3.     var result = false;
  4.     console.log(‘i = ‘ + i);
  5. }

The block statement is used by other statements such as the if-statement or for-statement. We will see these statements below.

Conditional statements

All the examples for this section are in this codepen (to run it: click on the “edit on CodePen” label, and once in CodePen, open the devtool console to see the outputs of this program):

(Please look, edit and try whatever you want. There are parts that are commented – please remove comments and try to understand the results).

Conditional statements are used to execute a unit of code 
only if a condition is evaluated as true.

The if statement

Syntax:

if ( Expression ) Statement else Statement

if ( Expression ) Statement

The expression may include:

  • logical operators ( ! && || )
  • comparison operators ( =====>>=<<= )
  • any values or expressions which can be converted to boolean
Example: if-statement
  1. var num = 10;
  2.  
  3. if (num === 10) {
  4.     num = 20;
  5. }
  6.  
  7. // num equals 20
Example: if-else statement
  1. var num = 10;
  2.  
  3. if (num > 10) {
  4.     num = 20;
  5. } else {
  6.     num = 0;
  7. }
  8.  
  9. // num equals 0

Reminder:

The following values will evaluate to false:

  • false
  • undefined
  • null
  • 0
  • NaN
  • “” (empty string)

All other values, including all objects, evaluate to true when passed to a conditional statement.

The if-then-else ternary operator

This ternary operator is a shortcut version of if…then…else.

Let’s look at this code example:

  1. var max;
  2. var min = 2;
  3.  
  4. if (min < 10) {
  5.     max = min + 10;
  6. } else {
  7.     max = min;
  8. }

Explanation: You can replace this “if-then-else” statement with the ternary operator that uses a syntax with “?” and “:”

  1. var max;
  2. var min;
  3. max = (min < 10)? min+10 : min;

Line 3 can be read as if (min < 10) then max = min+10, else max = min. The “then” part is after the “?” and the “else” part is after the “:” part.

This “short” version is not recommended except for very simple statements that involve a very obvious block of instructions for the “then” and the “else”. Usually this syntax is much harder to read for beginners.

Curly braces

Should we use them in if-then-else statements? There are examples without curly braces on the Web: what does this mean?

Here are two versions of the same code.

Version 1: no curly braces

  1. if (a > 2)
  2.     result = ‘a is bigger than 2’;
  3. else
  4.     result = ‘a is not bigger than 2’;

Version 2: with curly braces for delimiting the “then” and “else” blocks

  1. if (a > 2) {
  2.     result = ‘a is bigger than 2’;
  3. } else {
  4.     result = ‘a is not bigger than 2’;
  5. }

Version 1 and version 2 are equivalent. Indeed, version 1 is correct: you can omit curly braces if the “then” or “else” blocks are made of only one statement (one line of code).

But version 2 is cleaner and more readable, and, in particular, it is much better for maintainability (because you can add a statement just by pressing the enter key. And you can add some extra lines of code without worrying about adding curly braces because you broke the “1 line statement rule”).

So it is strongly recommended that you always use if-statements 
enclosed in curly braces. 

Of course, one-line if-statements like this :

  1. if (true) doSomething();

…are really fast to write, but if you want to add a second statement later it will become more time consuming.

Conclusion: always use curly braces!

The switch statement

In order to avoid having a series of ifs and elses, it is possible to use a switch statement. 

The syntax of the switch statement is:

  1. switch (expression) {
  2.     case value1:
  3.         statement
  4.         break;       // break can be omitted in that case
  5.                      // the second test case will be executed
  6.                      // most of the time we add a break; at the end
  7.                      // of a “case”
  8.  
  9.     case value2:
  10.         statement
  11.         break;
  12.  
  13.     case value3:
  14.         statement
  15.         break;
  16.  
  17.     default:         // if no case tested true
  18.         statement
  19.         break;
  20. }

If the value of an expression equals one of the cases (the equality operator evaluated is ===), all the statements next to this case block are executed sequentially until the keyword break is reached.

Example 1: a common switch/case/default example.

  1. var gear = ”;
  2.  
  3. switch (cloudColor) {
  4.     case ‘green’:
  5.         gear = ‘spacesuit’;
  6.         break;
  7.  
  8.     case ‘black’:
  9.         gear = ‘boots’;
  10.         break;
  11.  
  12.     case ‘grey’:
  13.         gear = ‘umbrella’;
  14.         break;
  15.  
  16.     case ‘white’:
  17.         gear = ‘jacket’;
  18.         break;
  19.  
  20.     default:
  21.         gear = ‘watch’;
  22.         break; // useless if in the last case
  23. } // end of the switch statement
  24.  

In this example, if the clouds are grey, then my gear will be just an umbrella. If they are white, I’ll wear only a jacket, if they are black I’ll be nude with just boots (!), and if they are green I’ll get a spacesuit. And if the cloud color is none of these, then I’ll only wear a watch. The presence of the break keyword at the end of the different cases make the choices 100% exclusive. Only one case can be executed!

Example 2: a switch without “breaks” at the end of each case.

  1. var gear = ”;
  2.  
  3. switch (cloudColor) {
  4.     case ‘green’:
  5.         gear += ‘spacesuit’;
  6.         break;
  7.  
  8.     case ‘black’:
  9.         gear += ‘boots, ‘;
  10.  
  11.     case ‘grey’:
  12.         gear += ‘umbrella, ‘;
  13.  
  14.     case ‘white’:
  15.         gear += ‘jacket, ‘;
  16.  
  17.     default:
  18.         gear += ‘watch’;
  19. } // end of the switch statement
  20.  

Explanation: if the clouds are black, then my gear will be ‘boots, umbrella, jacket, watch’. If the clouds are green, my gear is a spacesuit (because of the break keyword, other cases will not be tested). If the cloud color is not in the listed colors, then my gear is only a watch (default case).

To finish up this section, here is a complete example: three ways to do condition statements (to run it: click on the “edit on codepen” label and once in codepen, open the devtool console to see the outputs of this program):