JavaScript Operators - Exercise 2
The modulus operator (%) returns the
remainder after division, which is useful for cycles
and even-or-odd checks. For example, 7 % 2
is 1, so number % 2 === 0 tests for evenness.
The increment operator (++) adds one to
a variable. Prefix form updates first, while postfix
form returns the old value: let n = 1; n++;
leaves n equal to 2.
The decrement operator (--) subtracts
one from a variable. For example,
let attempts = 3; --attempts; changes
attempts to 2. Postfix
attempts-- would return the old value before
performing the same update.
Unary operators work with one operand rather than two,
and they can change a value, type, or boolean meaning.
Examples include typeof value, !isReady,
and -temperature.
Unary negation (-) changes a numeric
value's sign and converts numeric strings when possible.
For example, -8 is -8, and
-'8' is also the number -8.
Logical operators combine or invert conditions with
&&, ||, and !.
The first two can return an operand, so
name || 'Guest' supplies a fallback value.
The logical OR operator (||) returns the
first truthy operand, or the last operand when none is
truthy. For example, const label = input || 'Guest'
uses the fallback when input is empty.
Short-circuit evaluation stops as soon as a logical
result is known, which can avoid unnecessary work or
unsafe access. For example, user && user.name
reads name only when user is truthy.
The ternary operator chooses between two expressions
based on a condition and returns the selected value.
For example, online ? 'Online' : 'Offline'
produces a status label without a full if statement.
Use the syntax condition ? whenTrue : whenFalse
when each branch is a short expression. For example,
const status = online ? 'Online' : 'Offline'
assigns a label based on online.