JavaScript - Arithmetic Operators
Overview
Estimated time: 15–25 minutes
Perform math using arithmetic operators. Be mindful of floating-point precision and BigInt rules.
Learning Objectives
- Use arithmetic operators with Number and BigInt.
- Understand prefix vs postfix increment.
Prerequisites
Examples
2 + 3 // 5
7 - 4 // 3
6 * 7 // 42
7 / 2 // 3.5
7 % 2 // 1
2 ** 3 // 8
let x = 1;
let y = x++; // y = 1, x = 2 (postfix)
let z = ++x; // x = 3, z = 3 (prefix)
Precision
0.1 + 0.2 === 0.3 // false (floating point rounding)
BigInt
10n + 20n // 30n
// 10n + 1 // TypeError: Cannot mix BigInt and other types
Common Pitfalls
- Relying on exact floating-point sums; format or round if needed.
- Mixing BigInt and Number in the same expression throws.
Exercises
- Compute compound interest and discuss formatting the result to 2 decimals.
- Rewrite an expression to use
**
instead ofMath.pow
.