Tuesday 27 February 2018

How to use Nested if..else Statements in JavaScript

In JavaScript We can define one if..else statement into another. Such Statements are known as nested if..else statements. They are useful in situations when additional checking as or validation is is required. We can nest as many if...else statements within an if ....else statement as you want. In most cases an if..else statement is nested inside the else block of another if..else statement. Now here we create a Web page named NestedIf-ELSE-Statement.html which shows the use of nested if..else statements.


######Showing the code for the NestedIf-ELSE-Statement.html File #####
<!DOCTYPE html>
<html>
<head>
<title>Nested if...else Statement</title>
</head>
<body background="wall.jpg" text="blue">
<h1>
  Using If...Else Statement</h1>
<SCRIPT type="text/javascript">
var letter="I";
if(letter=="A")
document.write("vowel A");
else
if(letter=="E")
document.write("vowel E");
else
if(letter=="I")
document.write("vowel I");
else
if(letter=="o")
document.write("vowel o")
else
if(letter=="U")
document.write("vowel U");
else
document.write("consonant");
document.write("<BR/>Thank you!");
</SCRIPT>
</body>
</html>

The letter variable in the script is assigned the value I. The first if...else Statement has a condition (letter=="A") that checks whether the value of letter is equal to A. This condition is false therefore the first else block is executed which has a nested if..else statement inside it. The second if ..else statement has a condition that checks whether the letter is equal to E or not. This condition is also false therefore the second else block is executed. The second else block also has an if..else statement that checks whether or not letter is equal to I. This condition is true as a result the vowel I message is displayed.





No comments:

Post a Comment