JavaScript if-else Statement

If-else Statement is one of the conditional statement, that is used to decide the flow of execution on the basic of condition, If a condition is true, you can perform one action and if the condition is false, you can perform another action. However ‘else’ is optional with ‘if’ statement, if we want to perform on false condition also.

if-else diagram

Types of conditional statements

  1. If statement
  2. If – Else statement
  3. If…Else If…Else statement

If statement

The ‘if’ statement gets a condition evaluates it and if the result is true, executes the code

Syntax:

if (condition)
{
Statement/Code to be executed if condition is true
}

Example:

<html>
<head>
<script type=”text/javascript”>
var age = 25;
if(age>=18)
{
document.write(“You are an adult”);
}
if(age<18)
{
document.write(“You are NOT an adult”);
}
</script>
</head>
</html>


If – Else statement

else Statement is use to specify a block of code to be executed if the condition is false

Syntax:

if (condition)
{
Statement/Code to be executed if condition is true
}
else
{
Statement/Code to be executed if condition is false
}

Example:

<html>
<head>
<script type=”text/javascript”>
var age = 15;
if(age>=18)
{
document.write(“You are an adult”);
}
else
{
document.write(“You are NOT an adult”);
}
</script>
</head>
</html>


If…Else If…Else statement

else if statement specifies a new condition if the first condition is false

Syntax:

if (condition1)
{
Statement/Code to be executed if condition1 is true
}
else if(condition2)
{
Statement/Code to be executed if condition2 is true
}
else
{
Statement/Code to be executed if both condition1 and condition2 is false
}

Example:

<html>
<head>
<script type=”text/javascript”>
var total = 80;
if(total > 60)
{
document.write(“You got first division.”);
}
else if(total > 40)
{
document.write(“You got second division.”);
}
else
{
document.write(“You are fail.”);
}
</script>
</head>
</html>


Leave a Reply

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