Conditions in JavaScript

Date Published: 27/08/2020Published By: JaiSchool

Condition is a way that helps you to do the programming by applying condition constraints or lets you do programming according to your thinking. You need to know about conditional statements to work on it.

There are four conditional statements in Java-script to apply condition which are the following:

  1. if condition
  2. else condition
  3. if else condition
  4. switch() condition

if Condition

Its body's statements will execute when condition is true.

Example -

<!DOCTYPE html>
<html>
<head>
	<title>JS Conditions</title>
</head>
<body>

<input type="text" id="text">

<button onclick="demo()">Click</button>

<script>

function demo()
{
	var text_value = document.querySelector("#text").value;
	if(text_value.length > 6)
	{
		window.alert("You have entered more than 6 characters.");
	}
}

</script>
</body>
</html>

else Condition

When if condition is false then the else condition will execute.

if else Condition

Example-

<!DOCTYPE html>
<html>
<head>
	<title>JS Conditions</title>
</head>
<body>

<button onclick="demo()">Click</button>

<script>

function demo()
{
	if(window.screen.width < 450)
	{
		document.write("Your screen size is less than 450px");
	}
	else{
		window.alert("Your screen size is more than 450px");
	}
}

</script>
</body>
</html>

switch() Condition

Switch allows us to write multiple true conditions & one false condition at once.

Example-

<!DOCTYPE html>
<html>
<head>
	<title>JS Conditions</title>
</head>
<body>

<button onclick="demo()">Click</button>


<p id="demo"></p>

<script>
	
	switch(new Date().getMonth())
	{
		case 0:
		window.alert("This month is January");
		break;
		case 1:
		window.alert("This month is February");
		break;
		case 2:
		window.alert("This month is March");
		break;
		case 3:
		window.alert("This month is April");
		break;
		case 4:
		window.alert("This month is May");
		break;
		case 5:
		window.alert("This month is June");
		break;
		case 6:
		window.alert("This month is July");
		break;
		case 7:
		window.alert("This month is August");
		break;
		case 8:
		window.alert("This month is September");
		break;
		case 9:
		window.alert("This month is October");
		break;
		case 10:
		window.alert("This month is November");
		break;
		case 11:
		window.alert("This month is December");
		break;
		default:
		window.alert("Something is wrong");
	}

</script>
</body>
</html>

Other article on Java-script