Docs
Module-03-Operators
3.1 Arithmetic Operators
Table of Contents
- โขIntroduction
- โขBasic Arithmetic Operators
- โขAddition Operator
- โขSubtraction Operator
- โขMultiplication Operator
- โขDivision Operator
- โขModulo (Remainder) Operator
- โขExponentiation Operator
- โขUnary Operators
- โขIncrement and Decrement
- โขOperator Precedence
- โขSpecial Numeric Values
- โขCommon Patterns
- โขBest Practices
Introduction
Arithmetic operators perform mathematical calculations on numeric values. JavaScript supports all standard mathematical operations plus some additional features like modulo and exponentiation.
Quick Overview
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 15 / 3 | 5 |
% | Modulo/Remainder | 17 % 5 | 2 |
** | Exponentiation | 2 ** 3 | 8 |
++ | Increment | x++ | x + 1 |
-- | Decrement | x-- | x - 1 |
+ | Unary Plus | +"5" | 5 |
- | Unary Negation | -5 | -5 |
Basic Arithmetic Operators
The Five Fundamental Operations
ARITHMETIC OPERATIONS
Addition Subtraction Multiplication
โโโโโโโโโโ โโโโโโโโโโ โโโโโโโโโโ
โ 5 + 3 โ โ 5 - 3 โ โ 5 * 3 โ
โ = 8 โ โ = 2 โ โ = 15 โ
โโโโโโโโโโ โโโโโโโโโโ โโโโโโโโโโ
Division Modulo
โโโโโโโโโโ โโโโโโโโโโ
โ 15 / 3 โ โ 17 % 5 โ
โ = 5 โ โ = 2 โ
โโโโโโโโโโ โโโโโโโโโโ
Operator Characteristics
// All arithmetic operators:
// - Return a number (or NaN if operation fails)
// - Can work with numeric values or values that coerce to numbers
// - Follow mathematical rules (order of operations)
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); // 1000
Addition Operator
Basic Addition
// Number + Number
console.log(5 + 3); // 8
console.log(10.5 + 2.5); // 13
console.log(-5 + 3); // -2
console.log(-5 + -3); // -8
// Adding negative numbers
console.log(10 + -5); // 5 (same as 10 - 5)
String Concatenation
The + operator doubles as a concatenation operator for strings:
// String + String
console.log('Hello' + ' ' + 'World'); // "Hello World"
// String + Number = String (number converts to string)
console.log('Value: ' + 42); // "Value: 42"
console.log('5' + 3); // "53" (string!)
console.log(3 + '5'); // "35" (string!)
// Multiple operands - left to right
console.log(5 + 3 + '8'); // "88" (5+3=8, then "8"+"8"="88")
console.log('5' + 3 + 8); // "538" (strings all the way)
Addition with Special Values
console.log(Infinity + 1); // Infinity
console.log(Infinity + Infinity); // Infinity
console.log(-Infinity + Infinity); // NaN
console.log(NaN + 5); // NaN
Subtraction Operator
Basic Subtraction
console.log(10 - 5); // 5
console.log(5 - 10); // -5
console.log(-5 - 3); // -8
console.log(-5 - -3); // -2 (subtracting negative)
Type Coercion with Subtraction
Unlike +, the - operator ALWAYS converts to numbers:
console.log('10' - 5); // 5 (string "10" โ number 10)
console.log('10' - '5'); // 5
console.log('abc' - 5); // NaN
console.log(true - false); // 1 (true=1, false=0)
console.log(null - 1); // -1 (null โ 0)
console.log(undefined - 1); // NaN
Subtraction with Special Values
console.log(Infinity - 1); // Infinity
console.log(Infinity - Infinity); // NaN
console.log(-Infinity - -Infinity); // NaN
console.log(5 - NaN); // NaN
Multiplication Operator
Basic Multiplication
console.log(5 * 3); // 15
console.log(-5 * 3); // -15
console.log(-5 * -3); // 15
console.log(2.5 * 4); // 10
console.log(0.1 * 0.2); // 0.020000000000000004 (floating point!)
Type Coercion with Multiplication
console.log('5' * 3); // 15
console.log('5' * '3'); // 15
console.log(true * 5); // 5
console.log(false * 5); // 0
console.log(null * 5); // 0
console.log(undefined * 5); // NaN
console.log('abc' * 5); // NaN
Multiplication with Special Values
console.log(Infinity * 2); // Infinity
console.log(Infinity * -1); // -Infinity
console.log(Infinity * 0); // NaN
console.log(Infinity * Infinity); // Infinity
console.log(5 * NaN); // NaN
Division Operator
Basic Division
console.log(10 / 2); // 5
console.log(10 / 3); // 3.3333333333333335
console.log(-10 / 2); // -5
console.log(-10 / -2); // 5
console.log(10 / -2); // -5
Division by Zero
// Division by zero doesn't throw an error!
console.log(5 / 0); // Infinity
console.log(-5 / 0); // -Infinity
console.log(0 / 0); // NaN (indeterminate form)
Type Coercion with Division
console.log('10' / 2); // 5
console.log('10' / '2'); // 5
console.log(true / 2); // 0.5
console.log(null / 5); // 0
console.log(undefined / 5); // NaN
Division with Special Values
console.log(Infinity / 2); // Infinity
console.log(Infinity / Infinity); // NaN
console.log(5 / Infinity); // 0
console.log(-5 / Infinity); // -0 (negative zero!)
console.log(10 / NaN); // NaN
Modulo (Remainder) Operator
Understanding Modulo
The modulo operator returns the remainder after integer division.
Modulo Visualization:
17 % 5 = ?
17 รท 5 = 3 remainder 2
โโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโฌโโโโ
โ 1 โ 2 โ 3 โ 4 โ 5 โ 6 โ 7 โ 8 โ 9 โ10 โ11 โ12 โ13 โ14 โ15 โ16 โ17 โ
โโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโดโโโโ
โโโโโโโโโโโฌโโโโโโโโโโ โโโโโโโโโโโฌโโโโโโโโโโ โโโโโโโโโโโฌโโโโโโโโโโ โโโฌโโ
5 ร 1 = 5 5 ร 2 = 10 5 ร 3 = 15 remainder = 2
17 % 5 = 2
Basic Modulo Operations
console.log(17 % 5); // 2 (17 = 5*3 + 2)
console.log(10 % 3); // 1 (10 = 3*3 + 1)
console.log(10 % 5); // 0 (perfectly divisible)
console.log(5 % 10); // 5 (5 = 10*0 + 5)
Negative Numbers with Modulo
// Result takes the sign of the dividend (left operand)
console.log(-17 % 5); // -2
console.log(17 % -5); // 2
console.log(-17 % -5); // -2
Common Use Cases
// 1. Check if even or odd
let num = 7;
if (num % 2 === 0) {
console.log('Even');
} else {
console.log('Odd'); // This runs
}
// 2. Check divisibility
function isDivisibleBy(number, divisor) {
return number % divisor === 0;
}
console.log(isDivisibleBy(15, 3)); // true
console.log(isDivisibleBy(15, 4)); // false
// 3. Wrap around (cycling)
for (let i = 0; i < 10; i++) {
console.log(i % 3); // 0, 1, 2, 0, 1, 2, 0, 1, 2, 0
}
// 4. Get last digit(s)
console.log(12345 % 10); // 5 (last digit)
console.log(12345 % 100); // 45 (last two digits)
// 5. Keep value in range
let angle = 450;
let normalizedAngle = angle % 360; // 90
Modulo with Floating Point
console.log(5.5 % 2); // 1.5
console.log(10.5 % 3); // 1.5
console.log(2.5 % 1); // 0.5
console.log(5.5 % 1.5); // 1 (be careful with precision)
Exponentiation Operator
Basic Exponentiation
The ** operator was introduced in ES2016 (ES7).
// base ** exponent
console.log(2 ** 3); // 8 (2 ร 2 ร 2)
console.log(3 ** 2); // 9 (3 ร 3)
console.log(10 ** 0); // 1 (anything^0 = 1)
console.log(5 ** 1); // 5
console.log(2 ** 10); // 1024
Fractional and Negative Exponents
// Square root (^0.5)
console.log(25 ** 0.5); // 5
console.log(16 ** 0.5); // 4
// Cube root (^(1/3))
console.log(27 ** (1 / 3)); // 3
// Negative exponents (reciprocal)
console.log(2 ** -1); // 0.5 (1/2)
console.log(2 ** -2); // 0.25 (1/4)
console.log(10 ** -3); // 0.001
Comparison with Math.pow()
// These are equivalent:
console.log(2 ** 3); // 8
console.log(Math.pow(2, 3)); // 8
// But ** is right-associative:
console.log(2 ** (3 ** 2)); // 512 (2^(3^2) = 2^9)
console.log(Math.pow(Math.pow(2, 3), 2)); // 64 ((2^3)^2)
Edge Cases
console.log(0 ** 0); // 1 (mathematical convention)
console.log((-2) ** 2); // 4
console.log((-2) ** 3); // -8
// console.log(-2 ** 2); // SyntaxError! Need parentheses
console.log(Infinity ** 0); // 1
console.log(1 ** Infinity); // 1
Unary Operators
Unary Plus (+)
Converts operand to a number:
console.log(+5); // 5
console.log(+'5'); // 5 (string to number)
console.log(+''); // 0
console.log(+true); // 1
console.log(+false); // 0
console.log(+null); // 0
console.log(+undefined); // NaN
console.log(+'abc'); // NaN
console.log(+[]); // 0
console.log(+[5]); // 5
console.log(+[1, 2]); // NaN
Unary Negation (-)
Converts to number AND negates:
console.log(-5); // -5
console.log(-(-5)); // 5
console.log(-'5'); // -5
console.log(-true); // -1
console.log(-'abc'); // NaN
Practical Uses
// Quick string to number conversion
let str = '42';
let num = +str; // 42
// Toggle positive/negative
let value = 10;
value = -value; // -10
value = -value; // 10
// Convert to number in expressions
let input = '100';
let result = +input + 50; // 150 (number + number)
Increment and Decrement
Prefix vs Postfix
INCREMENT/DECREMENT TIMING
Prefix (++x, --x) Postfix (x++, x--)
โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ
โ First: Change โ โ First: Return โ
โ Then: Return โ โ Then: Change โ
โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ
Increment (++)
let x = 5;
// Postfix: returns original, then increments
console.log(x++); // 5 (returns 5, then x becomes 6)
console.log(x); // 6
// Prefix: increments, then returns
x = 5;
console.log(++x); // 6 (x becomes 6, returns 6)
console.log(x); // 6
Decrement (--)
let y = 5;
// Postfix
console.log(y--); // 5 (returns 5, then y becomes 4)
console.log(y); // 4
// Prefix
y = 5;
console.log(--y); // 4 (y becomes 4, returns 4)
console.log(y); // 4
Practical Examples
// Common loop patterns
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// Reverse loop
for (let i = 5; i > 0; i--) {
console.log(i); // 5, 4, 3, 2, 1
}
// Counter
let counter = 0;
function increment() {
return ++counter;
}
console.log(increment()); // 1
console.log(increment()); // 2
// Array index
let arr = [10, 20, 30];
let i = 0;
console.log(arr[i++]); // 10
console.log(arr[i++]); // 20
console.log(arr[i++]); // 30
Gotchas
// Don't use ++ on non-variables
let x = 5;
// 5++; // SyntaxError: Invalid left-hand side
// Multiple increments in one expression - avoid!
let a = 1;
// This is confusing - don't do this:
let b = a++ + ++a; // 1 + 3 = 4 (a is now 3)
// Clearer:
let c = 1;
c++;
c++;
let d = c; // 3
Operator Precedence
Arithmetic Precedence Rules
PRECEDENCE (high to low)
1. () Parentheses (grouping)
2. ** Exponentiation (right-to-left!)
3. + - Unary plus/minus
4. * / % Multiplication, Division, Modulo
5. + - Addition, Subtraction
Examples
// Without parentheses
console.log(2 + 3 * 4); // 14 (not 20)
console.log(10 - 4 / 2); // 8 (not 3)
console.log(2 ** 3 * 4); // 32 (8 * 4)
// With parentheses
console.log((2 + 3) * 4); // 20
console.log((10 - 4) / 2); // 3
console.log(2 ** (3 * 4)); // 4096 (2^12)
Associativity
// Left-to-right (most operators)
console.log(10 - 5 - 2); // 3 ((10-5)-2)
console.log(100 / 10 / 2); // 5 ((100/10)/2)
// Right-to-left (exponentiation)
console.log(2 ** (3 ** 2)); // 512 (2^(3^2) = 2^9)
Complex Expressions
// Break down step by step:
let result = 2 + (3 * 4 ** 2) / 8 - 1;
// Step 1: 4 ** 2 = 16
// Step 2: 3 * 16 = 48
// Step 3: 48 / 8 = 6
// Step 4: 2 + 6 = 8
// Step 5: 8 - 1 = 7
console.log(result); // 7
// When in doubt, use parentheses!
let clear = 2 + (3 * 4 ** 2) / 8 - 1;
console.log(clear); // 7
Special Numeric Values
Working with Infinity
console.log(Infinity + 1); // Infinity
console.log(Infinity - Infinity); // NaN
console.log(Infinity * 2); // Infinity
console.log(Infinity * 0); // NaN
console.log(Infinity / Infinity); // NaN
console.log(1 / Infinity); // 0
console.log(Infinity ** 0); // 1
Working with NaN
// Any arithmetic with NaN produces NaN
console.log(NaN + 5); // NaN
console.log(NaN * 10); // NaN
console.log(NaN / 2); // NaN
console.log(NaN ** 0); // 1 (only exception!)
// NaN is "contagious"
let value = parseInt('abc'); // NaN
console.log(value + 100); // NaN
Checking for Special Values
console.log(Number.isNaN(NaN)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(100)); // true
console.log(Number.isFinite(NaN)); // false
Common Patterns
Rounding Operations
// Round to nearest integer (use Math)
let num = 7.7;
console.log(Math.round(num)); // 8
console.log(Math.floor(num)); // 7 (round down)
console.log(Math.ceil(num)); // 8 (round up)
console.log(Math.trunc(num)); // 7 (remove decimals)
// Round to decimal places
let price = 19.99999;
console.log(Math.round(price * 100) / 100); // 20
console.log(price.toFixed(2)); // "20.00" (string!)
Random Numbers
// Random between 0 and 1
console.log(Math.random());
// Random integer between min and max (inclusive)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 10)); // 1-10
// Random from array
let items = ['a', 'b', 'c'];
let randomItem = items[Math.floor(Math.random() * items.length)];
Percentage Calculations
function percentage(part, whole) {
return (part / whole) * 100;
}
console.log(percentage(25, 100)); // 25
console.log(percentage(1, 3)); // 33.333...
function percentageOf(percent, total) {
return (percent / 100) * total;
}
console.log(percentageOf(20, 150)); // 30
Currency and Precision
// Floating point issues
console.log(0.1 + 0.2); // 0.30000000000000004
// Solution: Work in cents/smallest unit
let priceInCents = 199; // $1.99
let taxInCents = Math.round(priceInCents * 0.08); // 8% tax
let totalInCents = priceInCents + taxInCents;
let totalInDollars = totalInCents / 100;
console.log(`$${totalInDollars.toFixed(2)}`); // $2.15
Best Practices
1. Use Parentheses for Clarity
// Unclear
let result = a + (b * c) / d - e;
// Clear
let result = a + (b * c) / d - e;
2. Avoid String + Number Confusion
// Bad
let userInput = '5';
let result = userInput + 10; // "510" (string!)
// Good
let userInput = '5';
let result = Number(userInput) + 10; // 15
// or
let result = +userInput + 10; // 15
3. Check for NaN
// Bad
function calculate(x, y) {
return x / y;
}
// Good
function calculate(x, y) {
let result = x / y;
if (Number.isNaN(result) || !Number.isFinite(result)) {
throw new Error('Invalid calculation');
}
return result;
}
4. Handle Division by Zero
// Bad
function divide(a, b) {
return a / b; // Returns Infinity for b=0
}
// Good
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero');
}
return a / b;
}
5. Use Increment/Decrement Carefully
// Avoid confusing expressions
// Bad
let x = a++ + ++b - c--;
// Good
a++;
++b;
let x = a + b - c;
c--;
Summary
| Operator | Operation | Notes |
|---|---|---|
+ | Add / Concatenate | String if either operand is string |
- | Subtract | Always converts to number |
* | Multiply | Always converts to number |
/ | Divide | Division by 0 = Infinity |
% | Modulo | Remainder; takes sign of dividend |
** | Exponentiation | Right-to-left associative |
++ | Increment | Prefix vs postfix matters |
-- | Decrement | Prefix vs postfix matters |
+x | Unary plus | Convert to number |
-x | Unary minus | Convert and negate |
Next Steps
After mastering arithmetic operators, continue to: