compuhelpindia.com

JavaScript If...Else Statements

Compuhelpindia.com
« Previous                                                                                                                               Next Chapter »


Conditional statements are used to perform different actions based on different conditions.
If Statement
Use the if statement to execute some code only if a specified condition is true.
Eaxmple:
<!DOCTYPE html>
<html>
<body>
<script>
function compu()
{
var num;
num=parseInt(prompt("Enter The Number"));
if(num>0)
{
alert("Number is positive");
}
}
</script>
<p>Click one of the buttons to call a function</p>
<button onclick="compu()">Click for Compuhelp</button>
</body>
</html>  
 

Click one of the buttons to call a function

If...else Statement:
Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
function help()
{
var num;
num=parseInt(prompt("Enter The Number"));
if(num>0)
{
alert("Number is positive");
}
else
{
alert("Number is nagative");
}
}
</script>
<p>Click one of the buttons to call a function</p>
<button onclick="help()">Click for Compuhelp</button>
</body>
</html>  
 

Click one of the buttons to call a function

If...else if...else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
function vinod()
{
var num;
num=parseInt(prompt("Enter The Number"));
if(num>0)
{
alert("Number is positive");
}
else if(num<0)
{
alert("Number is nagative");
}
else
{
alert("Number is Zero");
}
</script>
<p>Click one of the buttons to call a function</p>
<button onclick="vinod()">Click for Compuhelp</button>
</body>
</html>  
 

Click one of the buttons to call a function