Create JavaScript Conditional Operators

Have you ever wanted to shorten a JavaScript "if" statement into one simple line? Read on and find out a neat way to shorten your short conditional statements (also called ternary statements).

Steps

  1. Declare your variables and whatnot: var numberOne = 1; var x;
  2. Use the question mark (?) and the colon (:) to create a conditional statement. After the question mark (?) you have two statements divided up by the colon (:). The first statement (before the colon) will be executed if the condition is true and the second (after the colon) if the condition is false.

      For example: (#1)

      This illustrates the short-hand way of creating the following "if" statement:

        x = (numberOne == 1) ? true : false;

      Normal one:

        if(numberOne == 1){
          x = true;
        }else{
          x = false;
        }

      An even shorter way of writing that would be:

        x = (number == 1);

      For example: (#2)

      If x is true, then doThis().

      Normal:

        if(x){
          doThis();
        }

      Shorthand:

        (x) ? doThis() : 0;

      Even shorter:

        x && doThis()

      For example: (#3)

      If x is false, then doThis().

      Normal:

        if(!x){
          doThis();
        }

      Shorthand:

        (!x) ? doThis() : 0;

      Even shorter:

        x || doThis()

  3. As in the if statement; not adding the : and the value after that, the statement will still work.

Warnings

  • If you need to do more than one operation on either side of the colon then don't use the conditional operator.
  • If other people are going to be reading and having to comprehend your script, try to avoid use of the ternary operator because it's unnecessarily hard to read.

Related Articles