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
- Declare your variables and whatnot: var numberOne = 1; var x;
- 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)
Ifx
istrue
, thendoThis()
.
Normal:
if(x){
doThis();
}
Shorthand:
(x) ? doThis() : 0;
Even shorter:
x && doThis()
For example: (#3)
Ifx
isfalse
, thendoThis()
.
Normal:
if(!x){
doThis();
}
Shorthand:
(!x) ? doThis() : 0;
Even shorter:
x || doThis()
- 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
- Use an Array Class in JavaScript
- Use JavaScript Injections
- Install Java on Linux
- Program in Java
- Install Java
- Use Graphics in a Java Applet