JavaScript if-else Statements. Learn What They Are And How To Use Them

Posted by TotalDC

Conditional statements in JavaScript are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform another action.

JavaScript conditional statements:

  • if statement
  • else-if statement
  • if…else if… else statement

If Statement

Syntax:

if (condition)
{
lines of code to be executed if condition is true
}

You can use If statement if you want to check only a specific condition.

Try this yourself:

<head>
	<title>IF Statments</title>
	<script type="text/javascript">
		const age = prompt("Please enter your age");
		if(age>=18){
		   console.log("You are an adult <br />");
                }
		if(age<18){
		   console.log("You are NOT an adult <br />");
                }
	</script>
</head>
<body>
</body>
</html>

If… Else Statement

Syntax:

if (condition)
{
lines of code to be executed if the condition is true
}
else
{
lines of code to be executed if the condition is false
}

You can use If….Else statement if you have to check two conditions and execute a different set of codes.

Try this yourself:

<html>
<head>
	<title>If...Else Statments</title>
	<script type="text/javascript">
		// Get the current hours
		let hours = new Date().getHours();
		if(hours<12){
		   console.log("Good Morning<br />");
                }
		else {
		   console.log("Good Afternoon<br />");
                }
	</script>
</head>
<body>
</body>
</html>

If… Else if … Else Statement

Syntax:

if (condition1)
{
lines of code to be executed if condition1 is true
}
else if(condition2)
{
lines of code to be executed if condition2 is true
}
else
{
lines of code to be executed if condition1 is false and condition2 is false
}

You can use If….Else If….Else statement if you want to check more than two conditions.

Try this yourself:

<html>
<head>
	<script type="text/javascript">
		let one = prompt("Enter the first number");
		let two = prompt("Enter the second number");
		one = parseInt(one);
		two = parseInt(two);
		if (one == two){
			   console.log(one + " is equal to " + two + ".");
                           }
		else if (one<two){
			   console.log(one + " is less than " + two + ".");
                           }
		else {
			console.log(one + " is greater than " + two + ".");
                     }
	</script>
</head>
<body>
</body>
</html>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: