Js Arithmetic in JavaScript
? JavaScript Arithmetic Operations
Basic Arithmetic Operators
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 7 | 42 |
/ | Division | 20 / 5 | 4 |
% | Modulus (Remainder) | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
Increment and Decrement
let x = 5;x++; // x = 6 (post-increment)++x; // x = 7 (pre-increment)x--; // x = 6 (post-decrement)--x; // x = 5 (pre-decrement)Compound Assignment Operators
let x = 10;x += 5; // x = x + 5 = 15x -= 3; // x = x - 3 = 12x *= 2; // x = x * 2 = 24x /= 4; // x = x / 4 = 6x %= 5; // x = x % 5 = 1Important Notes
Division by zero returns
Infinityor-Infinityin JavaScript, not an error.Modulus operator works with integers and floats, returns the remainder.
+operator also concatenates strings:
console.log(5 + "5"); // "55"console.log("5" + 5); // "55"Example
let a = 7;let b = 3;console.log(a + b); // 10console.log(a - b); // 4console.log(a * b); // 21console.log(a / b); // 2.3333...console.log(a % b); // 1console.log(a ** b); // 343Want me to cover Math object methods for more complex arithmetic, like rounding, random numbers, or trigonometry?