The javascript conditions statements are the most used statements. When facing some conditional situations in programming, where a certain block of code to be executed when some condition is fulfilled.
Conditional statements are also known as decision-making statements. Which are used to making a decision and executes a block of codes based on certain conditions.
There are mainly three types of conditional statements in JavaScript that you can use to make decisions:
If
StatementThe if statement executes a block of code if a condition is true.
if (test condition)
{
code to be executed if condition is true
}
Let’s take example for if statement and check only a specific condition using if statement:
<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
var num = prompt("Solve :- 8+5");
if(num == 13)
document.write("Correct answer <br />");
if(num == 13)
document.write("Wrong answer <br />");
</script>
</head>
<body>
</body>
</html>
If Else
StatementWhen the if test condition evaluates to false. Then execute else statement block of code.
if (test condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
Let’s take example for If Else statement:
<html>
<head>
<title>IF ELSE Statments!!!</title>
<script type="text/javascript">
var num = 13;
if(num == 12){
document.write("Execute If Statement<br />");
}else{
document.write("Execute Else Statement<br />");
}
</script>
</head>
<body>
</body>
</html>
If..Else If..Else
StatementWhen test multiple conditions after if statement. Then use Else If statement.
if (test condition1)
{
code to be executed if condition1 is true
}
else if(test condition2)
{
lines of code to be executed if condition2 is true
}
else
{
code to be executed if condition1 is false and condition2 is false
}
Let’s take example for if statement and check multiple conditions:
<html>
<head>
<title>IF ELSE If Else Statments!!!</title>
<script type="text/javascript">
var num = 13;
if(num == 12){
document.write("Execute If Statement<br />");
}else if(num == 13){
document.write("Execute Else If Statement<br />");
}else{
document.write("Execute Else Statement<br />");
}
</script>
</head>
<body>
</body>
</html>
#javascript #web-development