JavaScript supports various conditional statements that perform different actions based on a set of conditions. JavaScript executes a block of code based on certain JavaScript Conditions and continues executing till all the conditions are met. There are four decision making statements in JavaScript.
JavaScript Conditions Statements
if statement
else statement
else if
Switch Statement
if statement
Description
The condition code will be executed only when the given condition is true in JavaScript Conditions, otherwise, the program skips the execution part of that particular block.
Syntax
if(condition)
{
//statements;
}
Flow Chart
Examples
[html]
<!Doctype html>
<html>
<head>
<title>Conditional Statements</title>
<h2 style="color: grey">Example for if statement</h2>
</head>
<body>
<script type="text/javascript">
var a = 5;
if(a < 10)
{
document.write("GoodMorning");
}
</script>
</body>
</html>[/html]
Output
if..else statement
Description
if...else code will be executed only when the given condition in the "if" block istrue, otherwise it executes the statements of "else" block.
[c]
<!Doctype html>
<html>
<head>
<title>Conditional Statements</title>
<h2 style="color: grey">Example for if...else statement</h2>
</head>
<body>
<script>
var num1,num2,sum,res;
num1 = Number(prompt('Enter the first number : '));
num2 = Number(prompt('Enter the first number : '));
sum = num1 + num2;
if (sum == 20)
{
document.write("Sum is equal to 20");
}
else
{
document.write("Sum is not equal to 20");
}
</script>
</body>
</html>[/c]
Output
else-if...else statement
Description
else-if...else checks more than one condition. When the condition of first if statement is false, then it checks for the next else-if block. If true, then it executes the statements of inner else-if block, otherwise, executesthestatements of else block.
[c]
<!Doctype html>
<html>
<head>
<title>Conditional Statements</title>
<h2 style="color: Green">Example for else-if statement</h2>
</head>
<body bgcolor = "#E6E6FA">
<script>
var vehicle = "Car";
if (vehicle == "Car")
{
alert("You will go by Car");
}
else if(vehicle == "Aeroplane")
{
alert("You will go by Aeroplane");
}
else
{
alert("You will go by some other vehicle");
}
</script>
</body>
</html>
[/c]
Output
Switch Statement will be explained in further chapters.
Summary
Key Points
If statement helps in decision making.
“If” block will be executed only when the set of JavaScript Conditions are true.
If-else statement has both true and false options.