Nested ‘If’ Statements in JavaScript

This tutorial explains how to create nested IF statements in JavaScript. A nested IF statement is an IF statement that is inside another IF statement. Also known as…ifception 😉 Using nested IF statements is not always the best way to code but it is handy to know them anyway. View the video below or click here to watch it on YouTube.

You can also view the previous tutorial on ‘if’ statements and see which operators can be used in JavaScript here.

The sample code below shows how to use if statements inside other if statements (nested if statements).

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 var age = 21;
 var maxAge = 30;
 var minAge = 18;
 
 // Below is an example of using if statements inside other if statements
 // This is called nested if statements.
 
 if(age>=minAge){
 if(age<=maxAge){
 document.write("You are within the accepted age range.");
 }
 else{
 document.write("You are above the accepted maximum age.");
 }
 }
 else{
 document.write("You are under the accepted minimum age.");
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Using and/or operators in a complex If statement

Leave a Reply