iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Arithmetic

JavaScript has all the usual arithmetic operators, plus a few that catch beginners — modulo, exponentiation, and the prefix/postfix increment quirks.

Operators

OperatorMeansExample
+ - * /Add / subtract / multiply / divide7 / 2 → 3.5 (float)
%Remainder (modulo)7 % 3 → 1
**Exponentiation2 ** 10 → 1024
++ / --Increment / decrementx++ 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;

Test yourself

Q1. Exponentiation operator is…
Q2. Modulo (remainder) operator is…
Q3. `x++` returns…

Discussion

Loading…