Java script – conditional statement

Java script has many conditional statements. It is used to check whether the given condition is true or false.

It has following type.

  • ·       If
  • ·       If else
  • ·       If else if

Each one is explained as follows.

1.    If statement:

This is a simple condition checking statement. It has a syntax to follow.

Syntax:

If (condition)

{

Code….

}

 Example:

  if( a>10)

   {

        document.writeln(“The number is greater than 10”);

   }

This example checks the given number is greater than 10. If the condition is true,it prints the number is greater than 10.

Next, a simple example which checks the given number is greater than 10 or not is shown below.

2.    if  else:

This type of conditional statement is used to check the condition. if the condition is true,it goes to the if block. otherwise, the control is transferred to else block.

Syntax:

if (condition)

{

Code….

}

else

{

Code….

}

 

Example:

if(a>10)

{

  document.write(“the number is greater than 10”);

}

else

{

 document.write(“The number is less than 10”);

}

 

3.    if else if:

This is the third type of conditional statement. It is used to check many conditions.

Syntax:

if (condition)

{

Code….

}

else if( condition)

{

Code….

}

else

{

Code…

}

Example:

if( a >10)

{

  document.write(“the number is greater than 10”);

}

else if (a == 0)

{

 document.write(“The number is equal to 10”);

}

else

{

 document.write(“The number is less than 10”);

}

These are the three different ways of conditional statement in java script.

No comments:

Post a Comment