React and Forms, The Ternary Operator

React and Forms, The Ternary Operator

React Docs - Forms

The Conditional (Ternary) Operator Explained

Forms - React

The Ternary Operator

  1. The condition is what you’re actually testing. The result of your condition should be true or false or at least coerce to either boolean value.
  2. A ? separates our conditional from our true value. Anything between the ? and the : is what is executed if the condition evaluates to true.
  3. Finally a : colon. If your condition evaluates to false, any code after the colon is executed.

     let isStudent = false;
     let isSenior = true;
     let price = isStudent ? 8 : isSenior ? 6 : 10
     console.log(price);
     // 6
    
  1. First we check to see if our patron is a student. Since isStudent is false, only the code after the first : is executed. After the : we have a new conditional:
  2. Our second conditional tests isSenior — since this is true, only the code after the ? but before the : is executed.
  3. price is then assigned the value of 6 which which we later log to the screen.

Return home