Arithmetic Operators
Arithmetic operators perform mathematical calculations on numbers.
Basic Operators:
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 15 / 3 | 5 |
| % | Modulus (remainder) | 17 % 5 | 2 |
| ** | Exponentiation | 2 ** 3 | 8 |
Increment/Decrement:
- ++variable (pre-increment): increment then return
- variable++ (post-increment): return then increment
- Same logic for -- (decrement)
Compound Assignment: Shorthand for operation + assignment:
- x += 5 equals x = x + 5
- x -= 5 equals x = x - 5
- x *= 5 equals x = x * 5
- x /= 5 equals x = x / 5
Operator Precedence: Just like math class: parentheses, exponents, multiplication/division, addition/subtraction (PEMDAS).
Code Examples
Arithmetic Operationsjavascript
// Basic arithmetic
let a = 10, b = 3;
console.log("Addition:", a + b); // 13
console.log("Subtraction:", a - b); // 7
console.log("Multiplication:", a * b); // 30
console.log("Division:", a / b); // 3.333...
console.log("Modulus:", a % b); // 1 (remainder)
console.log("Exponent:", a ** b); // 1000 (10^3)
// Integer division (floor the result)
console.log("Integer division:", Math.floor(a / b)); // 3
// Increment and decrement
let count = 5;
console.log("Original:", count); // 5
console.log("Post-increment:", count++); // 5 (then becomes 6)
console.log("After:", count); // 6
console.log("Pre-increment:", ++count); // 7 (incremented first)
// Compound assignment
let score = 100;
score += 10; // score = score + 10
console.log("After +=:", score); // 110
score *= 2; // score = score * 2
console.log("After *=:", score); // 220The modulus operator (%) is very useful for checking if numbers are even/odd or for cycling through values.
Quick Quiz
1. What is the result of 17 % 5?
2. What is the difference between ++x and x++?
Was this lesson helpful?