JavaScript Conditional Statement:
In every language we need to put some conditional logic, that is we need to perform an action according to a condition. JavaScript supports if , else, switch case and conditional operator for this purpose.
JavaScript Conditioanl Statements Example 1(if):
<html>
<head>
<title>
Variables in JavaScript
</title>
</head>
<body>
<script type="text/javascript">
var x=12;
if(x>10)
document.write("Greater than ten");
</script>
</body>
</html>
Output:
Greater than ten
Example 2(if-else):
<html>
<head>
<title>
Variables in JavaScript
</title>
</head>
<body>
<script type="text/javascript">
var x=12;
if(x>110)
{
document.write("Greater than ten");
}
else
{
document.write("Not greater than ten");
}
</script>
</body>
</html>
Output:
Not greater than ten
Example 3 (if-elseif-else):
<html>
<head>
<title>
Variables in JavaScript
</title>
</head>
<body>
<script type="text/javascript">
var x=10;
if(x<10)
{
document.write("Less than ten");
}
else if(x==10)
{
document.write("Equal to ten");
}
else
{
document.write("Greater than ten");
}
</script>
</body>
</html>
Output:
Equal to ten
Example 4 (Switch Case):
<html>
<head>
<title>
Variables in JavaScript
</title>
</head>
<body>
<script type="text/javascript">
var x=10;
switch(x)
{
case 1:
document.write("One");
break;
case 2:
document.write("Two");
break;
case 3:
document.write("Three");
break;
case 4:
document.write("Four");
break;
case 5:
document.write("Five");
break;
case 6:
document.write("Six");
break;
case 7:
document.write("Seven");
break;
case 8:
document.write("Eight");
break;
case 9:
document.write("Nine");
break;
case 10:
document.write("Ten");
break;
default:
document.write("Other");
}
</script>
</body>
</html>
Output:
Ten
Example 5 (Ternary Operator):
<html>
<head>
<title>
Variables in JavaScript
</title>
</head>
<body>
<script type="text/javascript">
var x=10;
y=32;
s=(x>y)?x:y;
document.write("Greater Number is="+s);
</script>
</body>
</html>
Output:
Greater Number is=32If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.