JS Arithmetic
JavaScript has all the usual arithmetic operators, plus a few that catch beginners — modulo, exponentiation, and the prefix/postfix increment quirks.
Operators
| Operator | Means | Example |
|---|---|---|
+ - * / | Add / subtract / multiply / divide | 7 / 2 → 3.5 (float) |
% | Remainder (modulo) | 7 % 3 → 1 |
** | Exponentiation | 2 ** 10 → 1024 |
++ / -- | Increment / decrement | x++ or ++x |
Unary + | Coerce to number | +"5" → 5 |
Unary - | Negate | -x |
Prefix vs. postfix
JS
let x = 5; const a = x++; // a = 5 (use old value, THEN increment) const b = ++x; // b = 7 (increment FIRST, then use) // x is now 7
Watch out for these
JS
// Integer division — there isn't a dedicated operator Math.floor(7 / 2) // 3 7 / 2 | 0 // 3 (bitwise hack, integers only) // True modulo (handles negatives) ((n % m) + m) % m // 0.1 + 0.2 still equals 0.30000000000000004
Tip: Avoid
x++ inside larger expressions. arr[i++] reads short but hides a side effect. Increment on its own line.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Arithmetic!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Use the exponentiation operator to compute 2 to the 10th power.
const k = 2
10;
Two asterisks.
Discussion
Loading…