JavaScript Conditional Statements

Conditional Statements are used to decide the flow of statements execution. If the condition is true one block of  statements execute and if the condition false then another block of statements will execute.

Different Types of Conditional Statements

  1. If Statement
  2. If..Else Statement
  3. If..Else-If..Else Statement

1. If Statement:- when we have one condition to check we use if statement.

Syntax:-

if(condition)

{

If Block

will execute if the condition true

}

Example:-

var a = 10
        if(a>=15)

        document.write("a is greater than or equal to 15");

        if(a<15)

        document.write("a is less than 15");

In above example second if block will execute.

2. If..Else Statement:-  if.. else statement can be used when we have two condition to be checked and for each condition we have different set of statement execution.

Syntax:-

if (condition)

{
if block
will execute if the condition is true

}

else

{
else block
will execute if the condition is false

}

Example:-

var a= 10;

var b = a % 2;

if ( b == 0 )

{

document.write("a is Even");

}

else

{

document.write("a is Odd");

}

In above example a is even and after modulus by 2 remainder will be 0 therefor if block will execute.

3. If..Else-if..Else Statement:- We can use this conditional statement when we have more than two condition to check.

Syntax:-

if (condition1)

{

if block
will execute if condition1 is true

}

else if(condition2)

{

else if block
execute if condition2 is true

}

else

{

else block
will execute if condition1 and condition2 are false

}

Example:-

var a = 10 , b = 10;

if (a < b)

{
document.write("a is less than b");
}

else if (a == b)

{
document.write("a is equal to b");
}

else

{
document.write("a is greater than b");
}

In above example a and b are both equal to 10 therefore else if block will execute.