Home Free Templets Works Mind Chiller Photo Gallery Family & Friends Links
 
 
   
     
           
   
Javascript Basics Part-4 (If-Else )
     
           
   


Conditional Statement : If-Else

Most of our real life actions depends on some condition(s) , like , I shall eat if I am hungry, Bring umbrella if it is raining. In programming also we heavily use conditional statements , i.e., If-Else statements. Unfortunately, HTML can not provide this facility to us, so fill in this gap we have to use JavaScript.

The, syntax of If-Else in JavaScript goes like this,

If(condition)
{
//if condition is true execute this block
}
else{
// condition is false , thus execute this part
}

Program example :


<html>
<body>
<script language=javascript>
var x;
x=10;
if (x==10) // remember you should write = = inside condition
{document.write("value of x is 10");
}
else
{document.write("value of x is not 10");
}
</script>
</body>

The above code is self explanetory.

You can also get the value of "x" from the user

<html>
<body>
<script language=javascript>
var x;
x=window.prompt("Give a value of x");
if (x==10)
{document.write("value of x is 10");
}
else
{document.write("value of x is not 10");
}
</script>
</body>

Some times , we get into situations like this
"I shall go out, if I am hungry and if it is not raining." Here "going out" depends on two conditions and both the conditions must be true for going out.

In JavaScript also we can handle this type of situations where some actions depends on more tahn one conditions to be simultenously true. In these cases we can combine two or more conditions using the symbol "&&".

<html>
<body>
<script language=javascript>
var x;
x=window.prompt("Give marks");
if ((x<=100) && (x>=90))
{document.write("your grade is A");
}
else
{document.write("your grade is not A ");
}
</script>
</body>

Here , the marks should be <=100 and also >=90 to call it grade 'A'.

There is also A symbol "||" , which is used when any of the condition is true.









So , that's it . Hope you have enjoyed the tutorial. Thank You.


Back to Tutorial Index page

Your comments are most welcome admin@koderguru.com