JavaScript Arithmetic Operators
Arithmetic operators perform mathematical operations on numbers. JavaScript supports all the standard arithmetic operations plus exponentiation and modulus.
Basic Arithmetic Operators
The basic arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These work the same as in regular mathematics.
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 10 - 4 | 6 |
| * | Multiplication | 3 * 7 | 21 |
| / | Division | 15 / 3 | 5 |
| % | Modulus (Remainder) | 10 % 3 | 1 |
| ** | Exponentiation | 2 ** 3 | 8 |
let a = 10;
let b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.3333333333333335
console.log(a % b); // 1
console.log(a ** b); // 1000Modulus and Exponentiation
The modulus operator (%) returns the remainder of a division. The exponentiation operator (**) raises the left operand to the power of the right operand.
// Modulus - useful for checking even/odd
console.log(10 % 2); // 0 (even)
console.log(11 % 2); // 1 (odd)
console.log(17 % 5); // 2
// Exponentiation
console.log(2 ** 4); // 16
console.log(3 ** 3); // 27
console.log(25 ** 0.5); // 5 (square root)Increment and Decrement
The increment operator (++) adds 1 to a variable. The decrement operator (--) subtracts 1. Both have prefix and postfix forms that behave differently.
let x = 5;
// Postfix: returns value THEN increments
console.log(x++); // 5 (returns 5, then x becomes 6)
console.log(x); // 6
// Prefix: increments THEN returns value
console.log(++x); // 7 (x becomes 7, then returns 7)
console.log(x); // 7
// Decrement works the same way
console.log(x--); // 7 (returns 7, then x becomes 6)
console.log(x); // 6
console.log(--x); // 5 (x becomes 5, then returns 5)Operator Precedence
Operator precedence determines the order in which operations are performed. Multiplication and division have higher precedence than addition and subtraction. Use parentheses to control the order.
// Multiplication before addition
let result1 = 2 + 3 * 4;
console.log(result1); // 14 (not 20)
// Parentheses override precedence
let result2 = (2 + 3) * 4;
console.log(result2); // 20
// Exponentiation before multiplication
let result3 = 2 * 3 ** 2;
console.log(result3); // 18 (2 * 9)
// Complex expression
let result4 = 10 + 20 / 5 - 2 * 3;
console.log(result4); // 8 (10 + 4 - 6)Math with Special Values
JavaScript handles special numeric values like Infinity and NaN. Division by zero does not throw an error — it returns Infinity. Invalid math operations return NaN (Not a Number).
console.log(10 / 0); // Infinity
console.log(-10 / 0); // -Infinity
console.log(0 / 0); // NaN
console.log("hello" * 2); // NaN
console.log(NaN + 5); // NaN
// Check for NaN
console.log(isNaN("hello" * 2)); // true
console.log(isNaN(42)); // false
// Number.isFinite()
console.log(Number.isFinite(10)); // true
console.log(Number.isFinite(Infinity)); // false