CONDITIONAL STATEMENTS

Statement

Set of instructions is called a statement.

Conditional Statements

These statements will be executed when the condition given is met which means if the given condition is true then statements will get executed. If the condition is false, another statement will be executed.

In JavaScript we have following conditional statements :

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to select one of many blocks of code to be executed

Syntax of if conditional statement

if (condition) {
statements
}

Example :

let a = true;
if (a) {
console.log("This is true"); // Prints: This is true
}

In above example ‘a is true’ which means condition is met. So, code block will execute. If ‘a is false’ code block will not get execute as shown in below example.

let a = false;
if (a) {
console.log("This is true");
}

Syntax of if else conditional statement

if (condition) {
statements
} else {
statements
}

If you want to execute something when the condition is true and to execute something else when the condition is false then we can use if else conditional statement.

Example :

let a = false;
if (a) {
console.log("This is true");
} else {
console.log("This is false"); //Prints: This is false
}

Syntax of if else if conditional statement

if (condition 1) {
statements
} else if (condition 2) {
statements
} else {
statements
}

If you have multiple conditions to check then use if else if conditional statement.

Example :

let a = 20;
if (a < 10) {
console.log("a is less than 10");
} else if (a < 30) {
console.log("a is less than 30"); // Prints: a is less than 30
} else {
console.log("a is greater than 30");
}

switch

The switch statement contains multiple cases. A switch statement compares the value of the variable with multiple cases. If the value is matched with any of the cases, then the block of statements associated with this case will be executed.

For which each case, there will be one break which is used to come out of the loop.

This switch will have one default case which will be executed if no case is matched.

Syntax of switch conditional statement

switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}

Example :

let dice = 2;
switch (dice) {
case 1:
console.log("you got one");
break;
case 2:
console.log("you got two"); // Prints: you got two
break;
case 3:
console.log("you got three");
break;
default:
console.log("you did not roll the dice");
}