Can be used to shorten if/else operations. This comes in handy for returning a value quickly (i.e. in order to assign it to another variable).
In this case, result gets the 'cute' value, because the value of animal is 'kitty'. If animal had another value, result would get the 'still nice' value.
Compare this to what the code would like with if/else conditions.
The if or else conditions may have several operations. In this case the operator returns the result of the last expression.
Because a was equal to 0, it becomes 1, and str becomes 'not a test'. The operation which involved str was the last, so b receives the result of the operation, which is the value contained in str, i.e. 'not a test'.
Ternary operators always expect else conditions, otherwise you'll get a syntax error. As a workaround you could return a zero something similar in the else branch - this doesn't matter if you aren't using the return value but just shortening (or attempting to shorten) the operation.
As you see, if (a === 1) alert('Hey, it is 1!'); would do the same thing. It would be just a char longer, since it doesn't need an obligatory else condition. If an else condition was involved, the ternary method would be much cleaner.
Ternaries can be nested to encapsulate additional logic. For example
This is the same as the following if/else
Stylistically this should only be used with short variable names, as multi-line ternaries can drastically decrease
The only statements which cannot be used in ternaries are control statements. For example, you cannot use return or break with ternaries. The following expression will be invalid.
For return statements, the following would also be invalid:
To do the above properly, you would return the ternary as follows: