• Lessons Home
Topics
Community
  1. Lessons
  2. Flow Control
  3. Conditional Statements
  4. Nested Conditionals

      Nested Conditionals

      Nested Conditionals

      Sometimes one decision leads to another. Once you know a first condition is true, you may need to ask a second question before you can act. You can place an if statement inside another if statement. This is called nesting.

      An If Inside an If

      The inner if only runs when the outer condition is true:

      Boolean isLoggedIn = true;
      Boolean isAdmin = true;
      
      if (isLoggedIn) {
          if (isAdmin) {
              System.debug('Show the admin dashboard.');
          } else {
              System.debug('Show the normal dashboard.');
          }
      }
      

      Here the code never checks isAdmin unless the user is logged in. The inner decision is nested inside the outer one.

      Nesting With Else Branches

      An outer if / else can have completely different logic in each branch, including more conditionals:

      Integer age = 30;
      Boolean isMember = false;
      
      if (age < 13) {
          System.debug('Child price');
      } else {
          if (isMember) {
              System.debug('Member price');
          } else {
              System.debug('Standard price');
          }
      }
      

      Keep Nesting Shallow

      Nesting is powerful, but deeply nested if statements become hard to read. Two levels are usually fine. When you find yourself nesting three or four levels deep, it is often clearer to combine conditions with logical operators or use an else if chain instead.

      Why This Matters

      Real decisions often depend on more than one factor. Nested conditionals let you handle a first factor, then refine the outcome based on a second. Start with the broadest question on the outside and narrow down as you go in.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In