Understanding JavaScript Conditional Statements

Note: This post is work-in-progress learning-note and still in active development and updated regularly.

In a programming language, conditional statements are used to perform certain task repeatedly based on different conditions. For example, when writing codes, we would like to do different action for different situations.

Following conditional statements are commonly used in JavaScript:

  • If a specified condition is true, use if keyword to specify a block of code to be executed
  • If the same condition is false, use else keyword to specify a block of code to be executed
  • If the first condition is false, use else if keyword to specify other test condition
  • Use switch keyword to specify several alternative blocks of code to be executed

Based on the true or false outcome of certain actions different conditional statements are executed. Such conditional statements are integral part in a programming language to make decision, and logical flow control of program codes.

Following are some of the use cases for conditional statements:

  • To allow access to a private section of a website if user is has a valid access codes.
  • Submit a form if required fields are completed otherwise display error message
  • Check location of a user and display correct time based on the location of the user

In this learning-note post, we will cover some conditional statements including if, else, else if and tertiary operators. JS iteration (loops) is discussed in a separate post Understanding JavaScript Iterations (Loops).

If Statements

The if statement is fundamental to any conditional statements. To quote from the MDN, the if statement executes a statement if a specified condition is truthy; if the condition is falsy, another statement can be executed.”

Basic Syntax
//basic if syntax
if (condition) {
    // runs if condition is true

The syntax uses if keyword followed by condition in parentheses and block of codes within the curly brackets { }. A shorter form of it looks like: if () {}.

Use Case Example

In the example below, we check if the score of 94 is an A score. Score of is defined as 80 or above.

//initialize test score & grade
const score = 94;
const A = 80;

if (score >= 80) {
    console.log("Congrat! You got an A");
Congrat! You got an A

Since 94 is greater than 80, it passes the condition (line 5) and code block is executed with expected output message in the console (line 9). In the following example, lets change score value to 70 and evaluate condition if score is still A.

//re-initialize score value
const score = 70;
const A = 80;
//check if score is an A
if (score <= 80) {
   console.log("You didn't score A"); 
You didn't score A

Since score 70 is less than 80 and it passes the condition (line 14) and therefore executes block code to print the message in the console (line 18).

Else Statement

The Else statement is used together with the if statement. As discussed earlier, the if statement only executes when a condition returns true. Combined with else statement, when condition in if statement don’t pass and return false, then code blocks in the else statement are executed. The else statement do not contain any conditions.

Basic syntax
//basic syntax
if (condition) {
  statement_1; // runs if condition is true
} else {
  statement_2; // runs if condition is false

The else statement is followed after the if statement and it has no condition in parentheses.

Use Case Examples

The use of if followed by else statement is suitable for evaluating a conditions is true or false. If true run if statement code block and if false run else code block.

//initialize test score
const score = 75;
const A = 80;

if (score >= 80) {
    console.log("Congrat! You got an A");
} else {
   console.log("Sorry! You didn't score an A");
Sorry! You didn't score an A

In the example above, we evaluate whether score 75 is grade A or not. Because score 75 is not greater or equal to 80 it does not match the condition and returns false. Next it executes else statements code block and returns expected output as shown in line 11.

The if ..else statements can be applied to in many other situation, .. including to check user access as shown below.

//set user Id value
let userId = "smith05";

 //check valid userId
if (userId === "robert01") {
    console.log("Your username is valid");
} else {
    console.log("Not valid username. Try again.");
Not valid username. Try again.

In the example above, value of entered userID smith05 (line 2) is evaluated against the user’s stored set password robert01 (line 6).  Because the values do not match and fails strict equal evaluation test and moves to alternative else statement returns alternate message in console output (line 11).

TIP: It is advisable not to use simple assignment ( eg. x= y ) in conditional statements because it is confused with equality test. When there is a need, commonly it is put in additional parentheses eg. if ((x=y)) {  }.

Else..If Statement

The if and else statements discussed above evaluates a single conditional statement. If we want to evaluate multiple conditions, multiple if...else statements can be nested to create an else if clause.

Basic Syntax
// basic if..else syntax
if (condition_1) {
  statement_1; // runs if condition is true
} else if (condition_2) {
  statement_2;  // runs if condition is true
} else if (condition_n) {
  statement_n;  // runs if condition is true
} else {
  statement_last; // runs if condition is false

The else..if statement syntax contains a single if statement followed by multiple else if statements else statement if none of the conditions return true. The conditional statements are evaluated in order and if none of the conditions are true, then it executes the else statement.

TIP: There can be any number of else if statements. If there are many else if statements, use of switch statement is preferred for performance and readability.

Use Case Example

In the following example, adopted from Tania, several else if statements are used to evaluate letter grade from a test score.

// set current score
let score = 81;

// determine if grade is an A, B, C, D, or F
if (score >= 90) {
  console.log("You got an A grade");
} else if (score >= 80) {
  console.log("You got a B grade");
} else if (score >= 70) {
  console.log("You got a C grade");
} else if (score >= 60) {
  console.log("You got a D grade");
} else {
  console.log("Sorry! You got a F grade");
You got a B grade

In the example above, the if statement is evaluated first and 90 is higher than 81, it returns false and executes next conditional statement against 80 and in this case score 81 is greater than 80 it returns true and prints expected message in the console (line 17).

Although our score 81 is technically true also for C, D and F the execution stops at first condition that returns true and thus it returns expected B grade (line 17).

Conditional (ternary) Operator

The “ternary” or “question mark” operator can be used to write If..else conditional statements. It is a shorter syntax and is represented by using question mark ( ? ).

The quote from the MDN, “the conditional (ternary) operator is the only JS operator that takes three operands. This operator is frequently used as a shortcut for the if statement“.

Basic Syntax
//basic syntax
condition ? expr1 : expr2

//written with ? and : signs
(condition) ? runs if expression is true : runs if expression is false

The parameters used in the ternary operators are:

  • condition or conditions : It is an expression that evaluates true or false.
  • expr1, expr2 : Expression with value of anything.

If condition(s) is true, the operator returns the value of expr1, otherwise it returns the value of expr2.

Use Case examples

Lets look at below use of ternary operators case examples. First lets try to re-write an  If and else statements with ternary operators as shown below:

let userAccess = 21;
let age = 18;

// Check if User has an access
if (age >= userAccess) { 
  console.log("You may enter"); 
 } else { 
   console.log("Access denied."); 
//OUTPUT => Access Denied.

// initialize user age
let age = 18;

// initialize result of ternary operation in a variable
const userAccess = (age >= 21) ? "You may enter." : "Access denied.";
//acess userAcess
"Access denied."

In the example above, an example of If and else statement discussed in previous section is used to evaluate user access (lines: 1-11). When age value (18) is evaluated against userAccess value (21) in line 6, it does not match and returns false executes code block from else statement (line 9) and returns expected output (line 11).

The same code snippets is re-written using ternary operators in lines 15-22. First the question mark ( ? ) evaluates whether age is >=  21 and it fails the test and returns false. Next it runs after ( : ) and executes next statement returns the same out (line 22).

Use case: Multiple Ternary operators

Ternary operators can be used to evaluate multiple conditions as discussed under if..else statement section (above).

//initialize score
let score = 74;
//evaluate grade with ternary operator 
let grade = (score >= 90) ? 'It is an A' :
     (score >= 80) ? 'It is a B' :
     (score >= 70) ? 'It is a C' :
     (score >= 60) ? 'It is a D' :
     'Your score is a F';
//access grade
console.log(grade); // => It is a C

In the example above, the first question mark ( ? ) evaluates whether score (74) is >= 90. Since it is less than 90 and returns false and move past ( : ) and evaluates next condition whether score is >= 80 which also returns false. Next when it evaluates whether score is >= 70 and it’s a match and returns true and thus returns the expected output (line 10).

If use the same logic using if..else statement on the above code snippets, we get exactly the same output (line 24).

//evaluate score using if..else
if (score >= 90) {
    console.log('It is an A')
  } else if (score >= 80) {
    console.log('It is an B')
  } else if (score >= 70) {
    console.log('It is an C')
  } else if (score >= 60) {
    console.log('It is an D')
  } else {
    console.log( 'Your score is a F');
It is a C
Switch Statement

To quote from the MDN Documentationthe switch statement evaluates an expression, matching the expression’s value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.”

A switch statement could replace multiple use of if keyword in conditional statements. It is an alternative and more descriptive way to execute conditional statements.

Basic Syntax
//basic syntax
switch (expression) {
  case value1:
    code block // executed when value1 matches expression
  case value2:
    code block  // executed when value2 matches expression
  case value3:  // group cases
  case value4:
    code block  // executed when value3 and value4 matches expression
 case valueN:
    code block  // executed when valueN matches expression
    code block  // executed when no value matches expression

A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch" target="_blank" rel="noopener">switch</a> statement is used to select one of the the many conditions to be executed.

  • Expression: its value is matched against each clause (or case).
  • Case Value (optional): Block of codes used to match again the expression. If the expression matches (strict equality ===) the specified value, the statements inside the case clause are executed until either the end of the switch statement or a break.
  • Break: The break keyword breaks out of the block of codes and stops execution, if a match is found. This saves lot of execution time because it ignores rest of the codes.
  • Default (optional): It defines the block of codes to run if there is no match. It does not have to be last case in the switch andcan occur anywhere.
Use Case Example

The following use case example, adopted from the MDN Documentation, the switch statement is used to compare various conditions.

//initialize fruits variable
let fruits = 'Papayas';
switch (fruits) {
  case 'Oranges': 
    console.log('Oranges are $0.59 a pound.');
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    console.log('Sorry, we are out of ' + fruits + '.');
Mangoes and papayas are $2.79 a pound.

In the example above, the switch starts to compare fruits value papayas (line 2) from the case oranges (line 4) and the match fails. The switch continues to next case mangoes and the match fails again.  When the switch compares with next case papayas and that it is match (passes === test) and start executing block codes until it reaches break. It outputs correct return (line 15). Take a note that the block of code (line 9) is same for the case mangoes (line 7) and case papayas, these two cases are combined.

Tip: If the  blocks of codes in switch cases are same then they can be combined into one switch block.

The other use case examples of Switch statements can be:

  • To display a specific message corresponding to the day day of the week, as used by Tania Rascia.
  • To evaluate range of test score values and convert into a letter grade, as shown above under Else ..If section.
  • The MDN Documentation lists use case examples with multi-case single or chained operations.
Wrapping Up

Conditional statements are building blocks of all programming languages including JavaScript. In this learning-note post use of if, else, and else if keywords covering simple conditions, nesting different conditional statements, as well as use of the ternary conditional operator were discussed. Use of conditional statements in loops & iterations will be discussed separately.

NEXT: Learning JavaScript Loops & Iterations

Useful Resources & Links

While preparing this post, I have referred the following references extensively. Visit original link for additional information.