What are the mathematical operators in JavaScript, and what happens when an operand isn't a number?
JavaScript offers the usual math operators (+ - * / ** %) plus ++/--, and it tries to convert operands to numbers — failing with NaN when it can't.
The result of a mathematical operation is always a Number. The operators:
| Operator | Operation | Example |
|---|---|---|
+ |
Addition | 5 + 3 → 8 |
- |
Subtraction | 5 - 3 → 2 |
* |
Multiplication | 5 * 3 → 15 |
/ |
Division | 10 / 4 → 2.5 |
** |
Exponentiation (power) | 2 ** 3 → 8 |
% |
Modulo (remainder) | 10 % 3 → 1 |
++ |
Increment (add 1) | x++ means x = x + 1 |
-- |
Decrement (subtract 1) | x-- means x = x - 1 |
The % modulo operator returns the remainder of a division — handy for checking even/odd (n % 2 === 0) or wrapping around. ** raises to a power.
When you do math on a value that isn't a number, JavaScript first tries to convert it. If it can ('10' - 5 gives 5, because the string '10' becomes the number 10), great. If it can't, you get a special value NaN ("Not a Number"):
'10' - 5 // 5 — the string '10' became the number 10
'Hallo' - 7 // NaN — 'Hallo' can't become a number
NaN is JavaScript's way of saying "this math doesn't make sense," and it tends to silently spread through later calculations — a common source of bugs.