JavaScript
This page gently explains JavaScript arithmetic operators with small examples for addition, subtraction, multiplication, division, remainders, and powers.
Goal: understand the basic arithmetic operators and notice when strings and numbers behave differently.
Arithmetic operators
| Operator | Meaning | Example |
|---|---|---|
+ | Add, or join strings | 5 + 3 // 8 |
- | Subtract, or change a sign | 5 - 3 // 2 |
* | Multiply | 5 * 3 // 15 |
/ | Divide | 8 / 2 // 4 |
% | Remainder | 12 % 5 // 2 |
** | Power | 2 ** 3 // 8 |
Small examples
JavaScript
const total = 5 + 3;
const remainder = 12 % 5;
const square = 4 ** 2;
console.log(total); // 8
console.log(remainder); // 2
console.log(square); // 16When + joins text
If either side of + is a string, JavaScript joins the values as text. Convert input explicitly when you mean to calculate with numbers.
JavaScript
"5" + 3 // "53"
Number("5") + 3 // 8Common cautions
- Division by zero results in
Infinityfor numbers, while0 / 0isNaN; validate values when that matters. - Decimal calculations use floating-point numbers, so values such as
0.1 + 0.2may not equal exactly0.3. - Use parentheses when an expression's order is not obvious. They make the intended calculation easier to read.
++and--change a variable by one; use them carefully because prefix and postfix forms have different result timing.