• Lessons Home
Topics
Community
  1. Lessons
  2. Flow Control
  3. Conditional Statements
  4. Else and Else If

      Else and Else If

      Else and Else If

      A plain if statement runs code only when its condition is true. But often you also want to do something when the condition is false, or choose between several possibilities. That is what else and else if are for.

      The Else Block

      Add an else block to run code when the if condition is false. Exactly one of the two blocks runs:

      Integer score = 55;
      
      if (score >= 60) {
          System.debug('You passed.');
      } else {
          System.debug('You did not pass.');
      }
      

      Chaining With Else If

      When there are more than two outcomes, chain conditions with else if. Apex checks each condition in order from top to bottom and runs the block for the FIRST one that is true. Once a match is found, the rest are skipped:

      Integer score = 82;
      
      if (score >= 90) {
          System.debug('Grade: A');
      } else if (score >= 80) {
          System.debug('Grade: B'); // this runs
      } else if (score >= 70) {
          System.debug('Grade: C');
      } else {
          System.debug('Grade: F');
      }
      

      Order Matters

      Because the first true condition wins, put the most specific or highest conditions first. If you checked score >= 70 before score >= 90, every high score would match the 70 branch and the 90 branch could never run.

      The Final Else Is Optional

      The trailing else catches everything that did not match any earlier condition. You can leave it off if there is nothing to do in that case, but it is a good habit for handling the leftover situations.

      An if / else if / else chain lets your code pick exactly one path out of many.

      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