Using if – else in Javascript

The following if – else conditions in javascript:

  • if statement – simple if statement, executed when condition is true
  • if…else statement – statements are executed when condition is true or false
  • if…else if….else statement -  nested if – else statement which can b used for multiple blocks of code
  • switch statement -  simplified nested if – else statement

Syntax

if statment:

if (condition)
{
code to be executed if condition is true
}

if – else statement:

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

nested if – else statement:

if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}

switch statement:

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*