codescracker


javascript

JavaScript Conditional Statements



« Previous Tutorial Next Tutorial »


JavaScript conditional statements or decision making statements are used to perform particular actions based on the given conditions.

You will learn all about conditional statements in detail divided into the following three tutorials:

JavaScript Conditional Statements Example

Here is an example, demonstrates conditional statement in JavaScript:

<!DOCTYPE html>
<html>
<head>
	<title>JavaScript Conditional Statement Example</title>
	<script>
		if (new Date().getHours() < 9 && new Date().getHours() > 4)
		{
			document.getElementById("condition_para1").innerHTML = "Good Morning!";
		}
	</script>
</head>
<body>

<p>Display "Good Morning" if the hour is less than 9:00 a.m. and greater than 4:00 a.m., otherwise "Have a Good Day!".</p>
<p id="condition_para1">Have a Good Day!</p>

</body>
</html>

It will display "Good Morning!" if the time in between 4:00 am to 9:00 am, otherwise it will display as "Have a Good Day!"

Display "Good Morning" if the hour is less than 9:00 a.m. and greater than 4:00 a.m., otherwise "Have a Good Day!".

Have a Good Day!

Here is another example also uses conditional statement in JavaScript:

<!DOCTYPE html>
<html>
<head>
	<title>JavaScript Decision Making Statements</title>
	<script>
		function condition_fun2()
		{
			var timenow = new Date().getHours();
			if (timenow < 9 && time > 4)
			{
				document.getElementById("condition_para2").innerHTML = "Good Morning!";
			}
			else
			{
				document.getElementById("condition_para2").innerHTML = "Have a Good Day!";
			}
		}
	</script>
</head>
<body>

<button onclick="condition_fun2()">Greeting</button>
<p id="condition_para2"></p>

</body>
</html>

Below is the live demo output of the above decision making statements example program in JavaScript.

Here is an example on selection statements in JavaScript:

<!DOCTYPE html>
<html>
<head>
	<title>JavaScript Selection Statements Example</title>
	<script>
		function condition_fun3()
		{
			var timenow = new Date().getHours();
			if (timenow < 9 && time > 4)
			{
				document.getElementById("condition_para3").innerHTML = "Good Morning!";
			}
			else if(timenow > 15 && timenow < 21)
			{
				document.getElementById("condition_para3").innerHTML = "Good Evening!";
			}
			else
			{
				document.getElementById("condition_para3").innerHTML = "Have a good Day!";
			}
		}
	</script>
</head>
<body>

<button onclick="condition_fun3()">Greeting</button>
<p id="condition_para3"></p>

</body>
</html>

Here is the live demo output produced by the above JavaScript Selection Statements example program.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test