SimpleTuts.com

Nested if Statements in JavaScript

Nested if statements are if statements that are placed inside another if statement's block. They allow you to check for multiple conditions in a hierarchical manner.

Here's an example of nested if statements:


var age = 25;
var isStudent = false;

if (age >= 18) {
  console.log("You are an adult.");

  if (isStudent) {
    console.log("You are a student."); // This will not be executed in this example
  } else {
    console.log("You are not a student.");
  }
}

Explanation of the example:

All in one Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nested if else example</title>
</head>
<body>
    <form action="">
        <label for="">Enter a number</label>
        <input type="number" id="num">
        <button onclick="checksign();" type="button">Submit</button>
    </form>
    <script>
        function checksign(){
            var n = Number(document.getElementById('num').value);
            if(n>=0){
                if(n==0){
                    document.write("This is a neutral number");
                }else{
                    document.write("This is a positive number");
                }
            }else{
                document.write("This is a negative number");
            }
        }
    </script>
    
</body>
</html>
Run Code