If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Nested conditionals

Computer programs use conditionals to select the correct path for a program to go down. When a program only selects one of two paths, it can use a simple conditional (if/else). When a program selects one of many paths, it can use nested or chained conditionals.

Nested conditionals

Imagine a program that reports whether a number is positive, negative, or zero. That program needs to select from 3 paths.
The flowchart for the logic could look like this:
Flowchart with 2 diamonds, 3 rectangles, and 4 arrows.
  • Top diamond contains question "Is number larger than 0?"
  • From top diamond, an arrow marked true leads to rectangle with text "sign is positive."
  • From top diamond, an arrow marked false leads to diamond with question "Is number smaller than 0?"
  • From second diamond, an arrow marked true leads to rectangle with text "sign is negative."
  • From second diamond, an arrow marked false leads to rectangle with text "sign is neutral".
We can translate that into JavaScript using nested conditionals. Here's the equivalent JS:
var numberSign;

if (number > 0) {
  numberSign = "positive";
} else {
  if (number < 0) {
    numberSign = "negative";
  } else {
    numberSign = "neutral";
  }
}
📝 See similar code in: App Lab | Snap | Python
Our outer conditional is a simple if/else, corresponding to the top diamond in the flowchart. Then inside the else, we nest an inner conditional corresponding to the second diamond in the flow chart.
In text-based languages like JavaScript, it's important to pay attention to the syntax and formatting of your nested conditionals. Notice how I use curly brackets around every set of instructions and indent the inner conditional inside the else. That helps other programmers (including future me!) better understand the flow of the logic.
✏️ The program below compares the scores of two players and determines who has won, loss, or tied. Try changing the values around so that each player wins.
📝 See similar code in: App Lab | Snap | Python

Alternate nesting flows

For most nested conditionals, there are many possibilities for the order of the various conditions.
To decide if a number is positive/negative/neutral, we could also start off by asking if the number is equal to zero, like in this flowchart:
Flowchart with 2 diamonds, 3 rectangles, and 4 arrows.
  • Top diamond contains question "Is number equal to 0?"
  • From top diamond, an arrow marked true leads to rectangle with text "sign is neutral."
  • From top diamond, an arrow marked false leads to diamond with question "Is number larger than 0?"
  • From second diamond, an arrow marked true leads to rectangle with text "sign is positive."
  • From second diamond, an arrow marked false leads to rectangle with text "sign is negative".
Translated into JavaScript, that flow looks like this:
var numberSign;

if (number === 0) {
  numberSign = "neutral";
} else {
  if (number > 0) {
    numberSign = "positive";
  } else {
    numberSign = "negative";
  }
}
This flow is just as correct as the other flow and will output the same set of values for inputs as the first flow.
In fact, there are at least four more possible flows to achieve the same result.
Which flow should your program follow? As long as each of them achieve the same result, go for the flow that seems the most natural and intuitive. Once you've programmed the flow, always test your program with a range of values to make sure it works as expected.

Deeper nesting

It would be neat if everything in the world divided neatly into three categories, but the world's a messier place than that. Fortunately, we can nest conditionals as many levels as needed and our program can go down many different paths.
For example, we could write a program to classify a salsa into mild, medium, hot, or extreme, based on the Scoville rating of its peppers.
This flowchart describes the desired logic:
Flowchart with 3 diamonds, 4 rectangles, and 6 arrows.
  • Top diamond contains question "Is rating less than 5,000?"
  • From top diamond, an arrow marked true leads to rectangle with text "level is mild"
  • From top diamond, an arrow marked false leads to diamond with question "Is rating less than 20,000?"
  • From second diamond, an arrow marked true leads to rectangle with text "level is medium"
  • From second diamond, an arrow marked false leads to diamond with question "Is rating less than 70,000?"
  • From third diamond, an arrow marked true leads to rectangle with text "level is hot"
  • From third diamond, an arrow marked false leads to rectangle with text "level is extreme"
We can implement that in JavaScript with if/else statements like before, but with one additional level of nesting.
var level;

if (rating < 5000) {
  level = "mild";
} else {
  if (rating < 20000) {
    level = "medium";
  } else {
    if (rating < 70000) {
      level = "hot";
    } else {
      level = "extreme";
    }
  }
}
📝 See similar code in: App Lab | Snap | Python
Now our program can assign level to one of four different values, depending on what path is selected.
We need to be more careful about the ordering here, since each nested if assumes the program already checked the previous condition. We can't mix up the conditions as much as we could for the positive/negative/neutral program. Once again, always think carefully through your ordering when you're structuring your conditionals.
✏️ The program below is a simple daily calorie calculator for cats and dogs. Try changing the top variables to reflect your own pet, if you have one, or a friend's pet. You can also make the calculator more accurate by incorporating factors like whether your pet is overweight or indoor/outdoor. With nested conditionals, you can check anything!
📝 See similar code in: App Lab | Snap | Python

Chained conditionals

When we're programming, we often find ourselves using conditionals to check possible values of a single variable.
We've seen two examples of that already, and we can summarize each in a table:
conditionoutput
number > 0"positive"
number < 0"negative"
number === 0"neutral"
conditionoutput
rating < 5000"mild"
rating < 20000"medium"
rating < 70000"hot"
rating >= 70000"extreme"
Many programming languages include a way to write "chained" conditionals that are an even better way to check these values.
In the JavaScript language, we can chain conditionals using else if statements.
Here's how we can write the number sign checker with chained conditionals:
var numberSign;

if (number > 0) {
  numberSign = "positive";
} else if (number < 0) {
  numberSign = "negative";
} else {
  numberSign = "neutral";
}
📝 See similar code in: App Lab | Python
This code is very similar to the original code, but uses an else if instead of a nested else with an if inside it.
A chained conditional is generally easier to read, especially as the number of conditions increases, and often a bit shorter.
Here's the salsa level calculator written with chained conditionals:
var level;

if (rating < 5000) {
  level = "mild";
} else if (rating < 20000) {
  level = "medium";
} else if (rating < 70000) {
  level = "hot";
} else {
  level = "extreme";
}
📝 See similar code in: App Lab | Python
Compare that to the original version with nested conditionals. Flows much better, doesn't it?
Not all languages provide the ability to chain conditionals, but if you are programming in a language like JS or Python that does include the feature, do take advantage of it for cases like these.
📝 Exam Tip: The AP CSP exam does not include chained conditionals. It uses nested conditionals in all situations.

Nested conditionals in pseudocode

This pseudocode shows a simple nested conditional, with one outer IF/ELSE and one inner IF/ELSE:
IF (<condition 1>)
{
     <instructions 1>
} 
ELSE 
{
    IF (<condition 2>)
    {
         <instructions 2>
    } 
    ELSE 
    {
        <instructions 3>
    }
}
Here's the sign checking program in pseudocode:
IF (number > 0)
{
    numberSign ← "positive";
}
ELSE
{
    IF (number < 0)
    {
        numberSign ← "negative";
    }
    ELSE
    {
        numberSign ← "neutral";
    }
}

🙋🏽🙋🏻‍♀️🙋🏿‍♂️Do you have any questions about this topic? We'd love to answer— just ask in the questions area below!

Want to join the conversation?

  • aqualine seedling style avatar for user mat27hay
    Im 100 percent gonna fail this class
    (3 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user James Boniface
    what is the difference between chain and nested conditionals ''at ,
    (2 votes)
    Default Khan Academy avatar avatar for user
  • male robot hal style avatar for user anonymous
    me the only one here
    (4 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user rafaelm3610
    apple spruce apple pie 011011001
    (3 votes)
    Default Khan Academy avatar avatar for user
  • leaf red style avatar for user layaz7717
    In the pet calorie example, one of the coded lines was: "
    if (isNeutered) {
    println(1.6 * restingEnergyReq);
    } else {
    println(1.8 * restingEnergyReq);"
    How would you write the code if you wanted it to be true when the dog is NOT neutered?
    (0 votes)
    Default Khan Academy avatar avatar for user
  • ohnoes default style avatar for user OhNoesYouGotHacked
    I don't understand how you tell nested and chained conditionals apart
    (1 vote)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Pierre
    Thank you for providing this information for us all to learn. I am unclear how you are deciding when and where to "close" off a statement with "{" and "} with if/else statements after the first "if" and "else". Could you please provide some clarity?
    (1 vote)
    Default Khan Academy avatar avatar for user
    • leaf green style avatar for user Shane McGookey
      All if-else structures in the code will follow the same structure, i.e.

      if(condition) {
      do something...
      }
      else {
      do something else...
      }

      The above structure can become confusing when we deal with nested conditionals. However, you can remember the general syntactic structure of an if-else statement: if (condition) {} else {}. Therefore, you have if (condition) followed by one opening '{' and one closing '}'. Afterward, you have else followed by one opening '{' and one closing '}'. Regardless of nesting or the bodies of the if statements, this structure remains consistent.

      Let us try to follow this structure in code:

      if (condition) { // opening '{' (1st if)
      do something...
      } // closing '}' (1st if)
      else { // opening '{' (1st else)
      if (condition) { // opening '{' (2nd if)
      do something...
      } // closing '}' (2nd if)
      else { // opening '{' (2nd else)
      do something else...
      } // closing '}' (2nd else)
      } // closing '}' (1st else)

      The code above is a tad messy because it can be difficult to code in the context of a comment, but if you parse through it and take time to understand it you will observe the aforementioned repetitive structure. Once you get a handle on this structure, nested if-else statements will become natural to you. Also, do note that an "else" is not strictly necessary with each if statement, but I have always include an else to better match your specific question.
      (1 vote)
  • aqualine tree style avatar for user Alicedum23
    Are there chained conditionals for pseudocode?
    (1 vote)
    Default Khan Academy avatar avatar for user
  • leaf red style avatar for user layaz7717
    For the first negative, positive, neutral sign example, would one have to define "number" as a variable prior to running the rest of the code?
    (1 vote)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Lorenzo4soccer
    Im pretty confused on what else if means for chained conditionals? I understand what else and if are.
    (0 votes)
    Default Khan Academy avatar avatar for user
    • starky ultimate style avatar for user KLaudano
      Suppose we have some generic code as follows.

      '
      if(A){...}
      else if(B){...}
      else{...}
      '

      The program will first check if A is true. If it is true, then the program will run the subsequent block of code and that will be it. However, the program will only check if B is true (and possibly run its subsequent code) if A happens to be false. Finally, the program will execute the code after the else statement only when both A and B are false.
      (1 vote)