preferable to use the conditional operator instead of
if...else
. It produces more
compact code that is easier to read. For example:
if
(
isPrime
(
n
)) {
label
=
'prime'
;
}
else
{
label
=
'non-prime'
;
}
would be better written as:
label
=
isPrime
(
n
)
?
'prime'
:
'non-prime'
;
Converting if Statements to Short-Circuited Logical OR Expressions
Just as
if...else
statements that resolve to a value can easily be translated to condi‐
tional expressions,
if
statements that resolve to a value can easily be translated to
short-circuited logical OR expressions. This technique is not as obviously superior as
conditional operators over
if...else
statements, but you will see it quite often, so it’s
good to be aware of. For example,
if
(
!
options
)
options
=
{};
can be easily translated to:
options
=
options
||
{};
Conclusion
JavaScript, like most modern languages, has an extensive and useful collection of
operators, which will form the basic building blacks for manipulating data. Some, like
the bitwise operators, you will probably use very seldom. Others, such as the member
access operators, you won’t even normally think about as operators (where it can
come in handy is when you’re trying to untangle a difficult operator precedence
problem).
Assignment, arithmetic, comparison, and boolean operators are the most common
operators, and you’ll be using them frequently, so make sure you have a good under‐
standing of them before proceeding.
Conclusion | 101