Conditional Statements in Javascript


Published on: July 03, 2021 By T.Andrew Rayan

The conditional statements in javascript is used to execute set of statements based on condition.

To perform conditional check we use the following statements:

*) if statement

*) if-else statement

*) else-if statement

*) switch statement

if statement:

The if statement is used to execute a block of codes if the condition is true.

Syntax of if statement:

Example for if statement:

This will display "Good morning Sir" as output to the console.

if-else statement:

The if-else statement acts like a switch. It executes a block of codes in if statement, if the condition is true. If the condition is not satisfied then it will execute the block of codes in the else statement.

Syntax for if-else statement:

Example for if-else statement:

This will display "Good morning Madam" as output to the console.

else-if statement:

If there is a scenario to check more than 2 conditions then we need to go for else-if statement.

Syntax for else-if statement:

Example for else-if statements:

On executing this program it will display Good afternoon. Here we have checked 3 conditions and if any of the 3 condition is not satisfied then the else statement will be executed.

Here we have multiple conditions, so instead of going for else-if statement, we can prefer using the switch statement.

switch statement:

The switch statement can be used to check multiple condition and select any one of the condition to be executed. If no condition is satisfied, then it will execute the codes in the default block.

Syntax for switch statement:

Example for switch statement:

The switch statement can contain multiple case statements. Each statements have a set of codes. Once the codes are executed, we use break keyword to break from rest of the condition check.

So we can be assured that only one condition is executed inside a switch statement. If any of the conditions is not satisfied, then it will execute the block of codes in the default code block.


Most Read