Arithmetic Operators Explained
What are Arithmetic Operators?
Arithmetic operators are used to perform mathematical operations.
- Examples:
- Addition
- Subtraction
- Multiplication
- Division
- Increment / Decrement
List of Arithmetic Operators
| Operator | |
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus (remainder) |
** | Exponentiation (power) |
++ | Increment |
-- | Decrement |
Basic Example
let a = 10;
let b = 5;
console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2
console.log(a % b); // 0
console.log(a ** b); // power
Modulus Operator (%)
- Gives remainder
10 % 5 // 0
Exponentiation (**)
- Used for power
10 ** 2 // 100
Increment and Decrement
Post Increment (a++)
- First use value, then increase
let a = 10;
console.log(a++); // 10
console.log(a); // 11
Pre Increment (++a)
- First increase, then use value
let a = 10;
console.log(++a); // 11
Same for Decrement (--)
let a = 10;
console.log(a--); // 10
console.log(a); // 9
Important Difference (Interview)
| Type | |
a++ | Print first, then increment |
++a | Increment first, then print |
Tricky Interview Questions
1. String + Number
console.log("5" + 1); // "51"
- String concatenation happens
2. String - Number
console.log("5" - 1); // 4
- Converted to number
3. String * Number
console.log("5" * 2); // 10
4. Invalid String
console.log("abc" * 2); // NaN
- Not a Number
5. Boolean Addition
console.log(true + true); // 2
- true = 1, false = 0
6. Double Negative
console.log(5 - -2); // 7
7. Operator Precedence
console.log(5 + 2 * 10); // 25
- First multiplication →
2 * 10 = 20 - Then addition →
5 + 20 = 25
Key Points to Remember
- Only
+does string concatenation - Other operators convert values to numbers
NaNcomes when conversion is not possible- Pre and Post increment behave differently
- Operator precedence matters
Function Example from Code
function operations() {
let a = 10;
let b = 5;
console.log(a + b);
}