How to Create JavaScript Conditional Operators

Declare your variables and whatnot: var numberOne = 1; var x; ; , Use the question mark (?), As in the if statement; not adding the : and the value after that, the statement will still work.

4 Steps 1 min read Easy

Step-by-Step Guide

  1. Step 1: Declare your variables and whatnot: var numberOne = 1; var x; ;

    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() ,
  2. Step 2: Use the question mark (?)

  3. Step 3: As in the if statement; not adding the : and the value after that

  4. Step 4: the statement will still work.

Detailed Guide

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() ,

About the Author

J

Jeffrey Cole

Professional writer focused on creating easy-to-follow practical skills tutorials.

39 articles
View all articles

Rate This Guide

--
Loading...
5
0
4
0
3
0
2
0
1
0

How helpful was this guide? Click to rate: