Arithmetic Operators
Perform math with +, -, *, /, % and **.
Syntax
a + b
a % b
a ** bArithmetic operators perform calculations on numbers.
| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Remainder (modulus) |
** | Exponentiation |
Example
Loading editor…
Press Run to execute the code.
When to use it
- Calculate a shopping cart subtotal by multiplying item price by quantity and summing all lines.
- Determine which page of results to display by dividing total records by page size and using the remainder.
- Compute a percentage discount by dividing the discount amount by the original price and multiplying by 100.
More examples
Basic arithmetic operations
Uses multiplication and subtraction to compute a subtotal and apply a fixed discount.
const price = 49.99;
const qty = 3;
const subtotal = price * qty;
const discount = subtotal - 10;
console.log(subtotal, discount);Modulo for pagination
Uses division and modulo to compute page count and the number of items on the last page.
const totalItems = 53;
const pageSize = 10;
const totalPages = Math.ceil(totalItems / pageSize);
const remainder = totalItems % pageSize;
console.log(`${totalPages} pages, last page has ${remainder} items`);Exponentiation for area
Uses the exponentiation operator ** to square the radius when computing a circle's area.
const radius = 5;
const area = Math.PI * radius ** 2;
console.log(area.toFixed(2)); // 78.54
Discussion