2. If…Else Statements
Consider the following dummy code snippet for determining the strength of a password:
The intent of this code snippet is very simple — check if the password is more than 7 characters long. If it is, then set the
strength variable to
“Strong”, otherwise set it to
The previous code snippet can be shortened to the following:
This code snippet does exactly what the previous one does, all in just one line. This looks pretty good already. The following code snippet tries to review the evaluation of the conditional expression.
There is a better way of writing these kinds of
if...else conditional expressions — using the conditional operator also called the ternary operator. Its syntax looks like the following:
The previous code snippet can hence be rewritten using the ternary operator as follows:
Although the code snippet using logical operators works in a similar fashion as the snippet using the ternary operator (for this example), it is important to know that they are not substitutes.
It is much safer to use the ternary operator for cases like this except you really know what you are doing.
Consider the following code snippet to understand the danger of using logical operators for cases like this:
Here is another very familiar conditional statement that was usually found in cross-browser AJAX libraries.
Using logical operators, the previous code snippet can be rewritten like this (indentations are used to aid readability):
However, using the ternary operator, it can be written like this:
Notice in this code snippet that the ternary operator is nested, which is useful for dealing with more involved