Thursday, 15 May 2014

JavaScript If....Else Statements

JavaSript support the conditional statement which is used to perform the operation in a logical way.
Here in this post i teach you how the if \,ifelse and else if statements works or we can say that perform.


1) If Statement-


if (condition)

{

Statement(1) to be executed if condition is true

}

Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) are executed. If expression is false then no statement would be not executed. Most of the times you will use comparison operators while making decisions.

Example-

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
   document.write("<b>Hello My Name Is Amit!</b>");
}
//-->
</script>

Output is 

Hello My Name Is Amit!

2) If....Else Statement-


Instead of using two if statement we ll commonly used if....else statement.
For Example-

if(condition)
{

Statement  to be executed if condition is true

}

else
{

Statement  to be executed if condition is false
}


Now by the below example you know how to use if....else statement during the codes.

<script type="text/javascript">
<!--
var age = 25;
if( age > 20 ){
   document.write("<b>Amit completed engineering.</b>");
}else{
   document.write("<b>Does not completed</b>");
}
//-->
</script>

Output-

Amit completed engineering.

3) if...else if... statement-


This statement is used for several condition.

if (condition){
   Statement to be executed if condition 1 is true
}
else if (condition 2)
{
   Statement to be executed if condition 2 is true
}
else if (condition 3)
{
   Statement to be executed if condition 3 is true
}
else
{
   Statement to be executed if no condition is true
}

The above is the syntax of if...else if statement now i am going to show the another example for this so that you know it easily and try to practice more time you get clear about all the statements.

Example-

<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
   document.write("<b>History Book</b>");
}else if( book == "maths" ){
   document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
   document.write("<b>Economics Book</b>");
}else{
  document.write("<b>Unknown Book</b>");
}
//-->

</script>

Output-
Maths Book

Posted by- Amit Tiwari

No comments:

Post a Comment