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.
Step-by-Step Guide
-
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() , -
Step 2: Use the question mark (?)
-
Step 3: As in the if statement; not adding the : and the value after that
-
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
Jeffrey Cole
Professional writer focused on creating easy-to-follow practical skills tutorials.
Rate This Guide
How helpful was this guide? Click to rate: