const
doIt
=
false
;
const
result
=
doIt
?
"Did it!"
:
"Didn't do it."
;
If the first operand (which comes before the question mark—
doIt
, in this example) is
truthy, the expression evaluates to the second operand (between the question mark
and colon), and if it’s falsy, it evaluates to the third operand (after the colon). Many
beginning programmers see this as a more confusing version of an
if...else
state‐
ment, but the fact that it’s an expression and not a statement gives it a very useful
property: it can be combined with other expressions (such as the assignment to
result
in the last example).
Comma Operator
The comma operator provides a simple way to combine expressions: it simply evalu‐
ates two expressions and returns the result of the second one. It is convenient when
you want to execute more than one expression, but the only value you care about is
the result of the final expression. Here is a simple example:
let
x
=
0
,
y
=
10
,
z
;
z
=
(
x
++
,
y
++
);
In this example,
x
and
y
are both incremented, and
z
gets the value
10
(which is what
y++
returns). Note that the comma operator has the lowest precedence of any opera‐
tor, which is why we enclosed it in parentheses here: if we had not,
z
would have
received
0
(the value of
x++
), and then
y
would have been incremented. You most
commonly see this used to combine expressions in a
for
loop (see
) or to
combine multiple operations before returning from a function (see
).
Grouping Operator
As mentioned already, the grouping operator (parentheses) has no effect other than
to modify or clarify operator precedence. Thus, the grouping operator is the “safest”
operator in that it has no effect other than on order of operations.
Bitwise Operators
Bitwise operators allow you to perform operations on all the individual bits in a num‐
ber. If you’ve never had any experience with a low-level language such as C, or have
never had any exposure to how numbers are stored internally in a computer, you may
want to read up on these topics first (you are also welcome to skip or skim this sec‐
tion: very few applications require bitwise operators anymore). Bitwise operators
treat their operands as 32-bit signed integers in two’s complement format. Because all
numbers in JavaScript are doubles, JavaScript converts the numbers to 32-bit integers
before performing bitwise operators, and then converts them back to doubles before
returning the result.
Grouping Operator | 93