Share on Google+Share on Google+

JavaScript Conditional Statements

Advertisement
JavaScript Conditional Statements:Conditional statements are important feature of any programming language, like any other language JavaScript supports if, if else, if elseif else, switch case and ternary operator. In the present tutorial you will go through all these statements and examples will help you learn it in effective way.

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=32

Advertisements

Posted on: November 6, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.