Skip to main content

Mathematical Operators

Introduction​

Mathematical operators are the building blocks of calculations in programming. Whether you're building a calculator app, processing financial data, or creating a game with scoring, you'll use these operators constantly.

TypeScript provides the same mathematical operators as JavaScript, but with a crucial advantage: type safety . TypeScript checks at compile-time that you're performing mathematical operations on numbers, not accidentally mixing strings, booleans, or other types that would cause bugs.

Why Type Safety Matters for Math​

Let's see the difference:

JavaScript (no type checking):

let price = "100";
let tax = 20;
let total = price + tax;
console.log(total); // "10020" - Oops! String concatenation, not addition!

TypeScript (with type checking):

let price: number = 100;
let tax: number = 20;
let total: number = price + tax;
console.log(total); // 120 - Correct!

// This would be caught immediately:
// let badPrice: number = "100"; // ❌ Error: Type 'string' is not assignable to type 'number'

TypeScript saves you from these common mistakes before your code runs !​

The Number Type​

Before diving into operators, let's understand TypeScript's number type.

One Type for All Numbers​

Unlike languages like Java or C# that have separate types for integers (int) and decimals (float, double), TypeScript uses a single number type:

let age: number = 25; // Integer
let price: number = 19.99; // Decimal
let temperature: number = -5.5; // Negative decimal
let scientific: number = 1.5e6; // Scientific notation (1,500,000)

Special Number Values​

JavaScript (and TypeScript) has some special numeric values:

let infinite: number = Infinity; // Result of 1/0
let negInfinite: number = -Infinity; // Result of -1/0
let notANumber: number = NaN; // "Not a Number" - result of invalid operations

console.log(typeof NaN); // "number" - surprisingly, NaN is of type number!

// Checking for these values:
console.log(5 / 0); // Infinity
console.log(Math.sqrt(-1)); // NaN
console.log(Number.isNaN(NaN)); // true
console.log(Number.isFinite(Infinity)); // false

BigInt for Very Large Numbers​

For integers beyond the safe range of number (±2^53), use bigint:

let big: bigint = 9007199254740991n; // Note the 'n' suffix
let huge: bigint = BigInt("999999999999999999");

// You can't mix number and bigint:
let num: number = 100;
let bigNum: bigint = 100n;
// let invalid = num + bigNum; // ❌ Error: Operator '+' cannot be applied

Arithmetic Operators​

Basic Operations​

These are the fundamental arithmetic operators:

Addition (+)​

let sum: number = 5 + 3;
console.log(sum); // 8

let total: number = 10.5 + 4.3;
console.log(total); // 14.8

// Combining variables:
let a: number = 100;
let b: number = 50;
let result: number = a + b;
console.log(result); // 150

Subtraction (-)​

let difference: number = 10 - 3;
console.log(difference); // 7

let change: number = 100 - 37.50;
console.log(change); // 62.5

Multiplication (*)​

let product: number = 6 * 7;
console.log(product); // 42

let area: number = 5.5 * 3.2;
console.log(area); // 17.6

Division (/)​

let quotient: number = 20 / 4;
console.log(quotient); // 5

let precise: number = 10 / 3;
console.log(precise); // 3.3333333333333335

// Integer division (if you need whole numbers):
let wholeNumber: number = Math.floor(10 / 3);
console.log(wholeNumber); // 3

Watch out for division by zero:

let result: number = 5 / 0;
console.log(result); // Infinity (not an error!)

let invalid: number = 0 / 0;
console.log(invalid); // NaN

Modulus Operator (%)​

The modulus (or remainder) operator gives you what's left after division:

let remainder: number = 10 % 3;
console.log(remainder); // 1 (10 ÷ 3 = 3 remainder 1)

let evenCheck: number = 8 % 2;
console.log(evenCheck); // 0 (8 is evenly divisible by 2)

Real-world uses:

// Check if a number is even:
function isEven(num: number): boolean {
return num % 2 === 0;
}

console.log(isEven(4)); // true
console.log(isEven(7)); // false

// Get last digit of a number:
function lastDigit(num: number): number {
return num % 10;
}

console.log(lastDigit(12345)); // 5

// Cycle through values (like array indices):
let index: number = 7;
let arrayLength: number = 5;
let wrappedIndex: number = index % arrayLength;
console.log(wrappedIndex); // 2 (7 % 5 = 2)

Exponentiation (**)​

The exponentiation operator raises a number to a power:

let squared: number = 5 ** 2;
console.log(squared); // 25 (5²)

let cubed: number = 3 ** 3;
console.log(cubed); // 27 (3³)

let power: number = 2 ** 10;
console.log(power); // 1024 (2^10)

Alternative using Math.pow():

let result: number = Math.pow(2, 8);
console.log(result); // 256

// Both are equivalent, but ** is more concise

Increment and Decrement​

Increment (++)​

Increases a number by 1:

let count: number = 5;
count++; // count is now 6
console.log(count); // 6

Decrement (--)​

Decreases a number by 1:

let lives: number = 3;
lives--; // lives is now 2
console.log(lives); // 2

Prefix vs Postfix - Important Difference!​

The position of ++ or -- matters:

Postfix (x++) - Use the value, then increment:

let x: number = 5;
let y: number = x++; // y gets 5, then x becomes 6
console.log(x); // 6
console.log(y); // 5

Prefix (++x) - Increment, then use the value:

let a: number = 5;
let b: number = ++a; // a becomes 6, then b gets 6
console.log(a); // 6
console.log(b); // 6

In practice:

// Most common use (no difference between prefix/postfix):
let counter: number = 0;
for (let i = 0; i < 5; i++) {
counter++; // or ++counter - same effect here
}

// Where it matters:
let score: number = 10;
console.log(score++); // Prints 10, then increments
console.log(score); // Prints 11

let points: number = 10;
console.log(++points); // Increments to 11, then prints 11

Assignment Operators​

Basic Assignment (=)​

Assigns a value to a variable:

let x: number = 10;
let y: number = x; // y is now 10

Compound Assignment Operators​

These combine an operation with assignment:

Addition Assignment (+=)​

let score: number = 100;
score += 50; // Same as: score = score + 50
console.log(score); // 150

Subtraction Assignment (-=)​

let health: number = 100;
health -= 25; // Same as: health = health - 25
console.log(health); // 75

Multiplication Assignment (*=)​

let value: number = 5;
value *= 3; // Same as: value = value * 3
console.log(value); // 15

Division Assignment (/=)​

let total: number = 100;
total /= 4; // Same as: total = total / 4
console.log(total); // 25

Modulus Assignment (%=)​

let remainder: number = 17;
remainder %= 5; // Same as: remainder = remainder % 5
console.log(remainder); // 2

Exponentiation Assignment (**=)​

let base: number = 2;
base **= 8; // Same as: base = base ** 8
console.log(base); // 256

Operator Precedence​

Just like in math class, some operations happen before others:

  1. Parentheses ()
  2. Exponentiation **
  3. Multiplication, Division, Modulus *, /, %
  4. Addition, Subtraction +, -
let result1: number = 5 + 3 * 2;
console.log(result1); // 11 (not 16!) - multiplication first

let result2: number = (5 + 3) * 2;
console.log(result2); // 16 - parentheses force addition first

let result3: number = 10 + 5 * 2 ** 3;
console.log(result3); // 50 (2**3=8, then 5*8=40, then 10+40=50)

Pro tip: When in doubt, use parentheses to make your intention clear!


Type Safety in Action​

TypeScript prevents common mathematical errors:

Catching Type Mismatches​

let age: number = 25;
let name: string = "Alice";

// TypeScript catches this at compile time:
// let invalid = age + name; // ❌ Error: Operator '+' cannot be applied to types 'number' and 'string'

Function Parameters​

function calculateArea(width: number, height: number): number {
return width * height;
}

calculateArea(5, 10); // ✅ Returns 50
// calculateArea(5, "10"); // ❌ Error: Argument of type 'string' is not assignable
// calculateArea(5); // ❌ Error: Expected 2 arguments, but got 1

Return Types​

function divide(a: number, b: number): number {
if (b === 0) {
return 0; // Handling division by zero
}
return a / b;
}

// TypeScript ensures the function always returns a number
let result: number = divide(10, 2);

Common Math Utilities​

TypeScript includes JavaScript's Math object with useful functions:

Rounding​

let num: number = 3.7;

console.log(Math.floor(num)); // 3 - rounds down
console.log(Math.ceil(num)); // 4 - rounds up
console.log(Math.round(num)); // 4 - rounds to nearest
console.log(Math.trunc(num)); // 3 - removes decimal part

Min and Max​

console.log(Math.min(5, 2, 9, 1)); // 1
console.log(Math.max(5, 2, 9, 1)); // 9

Absolute Value​

console.log(Math.abs(-5)); // 5
console.log(Math.abs(5)); // 5

Random Numbers​

// Random number between 0 (inclusive) and 1 (exclusive)
let random: number = Math.random();

// Random integer between 1 and 6 (dice roll)
let dice: number = Math.floor(Math.random() * 6) + 1;

// Random integer between min and max (inclusive)
function randomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInt(1, 10)); // Random number from 1 to 10

Power and Square Root​

console.log(Math.pow(2, 8)); // 256 (same as 2 ** 8)
console.log(Math.sqrt(16)); // 4
console.log(Math.cbrt(27)); // 3 (cube root)

Concepts​

Quick Reference​

// Arithmetic operators
let sum = 5 + 3; // Addition: 8
let diff = 10 - 4; // Subtraction: 6
let product = 6 * 7; // Multiplication: 42
let quotient = 20 / 4; // Division: 5
let remainder = 17 % 5; // Modulus: 2
let power = 2 ** 3; // Exponentiation: 8

// Increment/Decrement
let x = 5;
x++; // x is now 6
x--; // x is back to 5
let y = ++x; // x becomes 6, y is 6
let z = x++; // z is 6, x becomes 7

// Assignment operators
let num = 10;
num += 5; // num = 15
num -= 3; // num = 12
num *= 2; // num = 24
num /= 4; // num = 6
num %= 4; // num = 2

// Type safety
function add(a: number, b: number): number {
return a + b;
}

Examples​

// Calculate BMI (Body Mass Index)
function calculateBMI(weight: number, height: number): number {
return weight / (height ** 2);
}

let bmi: number = calculateBMI(70, 1.75);
console.log(bmi.toFixed(2)); // 22.86

// Calculate discount
function applyDiscount(price: number, discountPercent: number): number {
return price - (price * discountPercent / 100);
}

let finalPrice: number = applyDiscount(100, 20);
console.log(finalPrice); // 80

// Convert temperature
function celsiusToFahrenheit(celsius: number): number {
return (celsius * 9/5) + 32;
}

console.log(celsiusToFahrenheit(25)); // 77

// Calculate compound interest
function compoundInterest(
principal: number,
rate: number,
years: number
): number {
return principal * (1 + rate) ** years;
}

let investment: number = compoundInterest(1000, 0.05, 10);
console.log(investment.toFixed(2)); // 1628.89

// Check if even or odd
function isEven(num: number): boolean {
return num % 2 === 0;
}

console.log(isEven(4)); // true
console.log(isEven(7)); // false

Challenges​

1. Rectangle Area Calculator​

  • Create a function calculateArea that takes length and width as parameters.
  • Return the area of the rectangle.
  • Test with length = 8 and width = 5.
💡 Show Answer
function calculateArea(length: number, width: number): number {
return length * width;
}

console.log(calculateArea(8, 5)); // 40

// Try with different values:
console.log(calculateArea(12, 4)); // 48
console.log(calculateArea(7.5, 3)); // 22.5

// TypeScript catches type errors:
// console.log(calculateArea("8", 5)); // ❌ Error: Argument of type 'string' is not assignable


2. Remainder Calculator​

  • Write a function that calculates the remainder when dividing two numbers.
  • Find the remainder of 23 ÷ 6.
  • Try with a few other number pairs.
💡 Show Answer
function getRemainder(dividend: number, divisor: number): number {
return dividend % divisor;
}

console.log(getRemainder(23, 6)); // 5
console.log(getRemainder(17, 5)); // 2
console.log(getRemainder(100, 7)); // 2
console.log(getRemainder(8, 2)); // 0 (evenly divisible)

// Real-world use: check if number is divisible
function isDivisibleBy(num: number, divisor: number): boolean {
return num % divisor === 0;
}

console.log(isDivisibleBy(10, 5)); // true
console.log(isDivisibleBy(10, 3)); // false

3. Power Calculator​

  • Create a function power that raises a base to an exponent.
  • Calculate 3⁴ (3 to the power of 4).
  • Try calculating 2¹⁰ and 5³.
💡 Show Answer
function power(base: number, exponent: number): number {
return base ** exponent;
}

console.log(power(3, 4)); // 81
console.log(power(2, 10)); // 1024
console.log(power(5, 3)); // 125

// Try negative exponents:
console.log(power(2, -2)); // 0.25 (1/4)

// Fractional exponents (roots):
console.log(power(16, 0.5)); // 4 (square root of 16)
console.log(power(8, 1/3)); // 2 (cube root of 8)


4. Temperature Converter​

  • Write a function that converts Celsius to Fahrenheit.
  • Formula: F = (C × 9/5) + 32
  • Convert 25°C, 0°C, and 100°C.
💡 Show Answer
function celsiusToFahrenheit(celsius: number): number {
return (celsius * 9/5) + 32;
}

console.log(celsiusToFahrenheit(25)); // 77°F
console.log(celsiusToFahrenheit(0)); // 32°F (freezing point)
console.log(celsiusToFahrenheit(100)); // 212°F (boiling point)
console.log(celsiusToFahrenheit(-40)); // -40°F (same in both scales!)

// Bonus: Fahrenheit to Celsius
function fahrenheitToCelsius(fahrenheit: number): number {
return (fahrenheit - 32) * 5/9;
}

console.log(fahrenheitToCelsius(77)); // 25°C
console.log(fahrenheitToCelsius(32)); // 0°C

5. Shopping Cart with Discount​

  • Create a function that calculates the total of three item prices.
  • Apply a discount percentage (default 15%).
  • Calculate the final price for items costing $100, $50, and $20.
💡 Show Answer
function calculateDiscountedTotal(
price1: number,
price2: number,
price3: number,
discountPercent: number = 15
): number {
const subtotal = price1 + price2 + price3;
const discount = subtotal * (discountPercent / 100);
return subtotal - discount;
}

console.log(calculateDiscountedTotal(100, 50, 20)); // 144.5 (15% off)
console.log(calculateDiscountedTotal(100, 50, 20, 20)); // 136 (20% off)
console.log(calculateDiscountedTotal(100, 50, 20, 0)); // 170 (no discount)

// Alternative implementation:
function applyDiscount(subtotal: number, discountPercent: number): number {
return subtotal * (1 - discountPercent / 100);
}

console.log(applyDiscount(170, 15)); // 144.5


6. Increment and Decrement Practice​

  • Start with a variable x = 10.
  • Increment it twice using ++.
  • Decrement it once using --.
  • Print the final value.
  • Experiment with prefix vs postfix notation.
💡 Show Answer
// Basic example:
let x: number = 10;
x++; // 11
x++; // 12
x--; // 11
console.log(x); // 11

// Exploring prefix vs postfix:
let a: number = 5;
console.log(a++); // Prints 5, then a becomes 6
console.log(a); // Prints 6

let b: number = 5;
console.log(++b); // b becomes 6, then prints 6
console.log(b); // Prints 6

// In a loop (no difference):
let count: number = 0;
for (let i = 0; i < 3; i++) { // or ++i, same effect
count++; // or ++count
}
console.log(count); // 3

// Where it matters:
let score: number = 10;
let bonus: number = score++ + 5; // bonus = 15, score = 11
console.log(score, bonus);

let points: number = 10;
let total: number = ++points + 5; // total = 16, points = 11
console.log(points, total);

7. Egg Carton Calculator​

  • Calculate how many dozen eggs (12 per dozen) fit into 50 eggs.
  • Find how many eggs are left over.
  • Return both values in an object.
💡 Show Answer
function calculateDozens(totalEggs: number): { dozens: number; leftover: number } {
return {
dozens: Math.floor(totalEggs / 12),
leftover: totalEggs % 12
};
}

const result = calculateDozens(50);
console.log(`Dozens: ${result.dozens}, Leftover: ${result.leftover}`);
// Dozens: 4, Leftover: 2

// Try with other values:
console.log(calculateDozens(36)); // { dozens: 3, leftover: 0 }
console.log(calculateDozens(100)); // { dozens: 8, leftover: 4 }
console.log(calculateDozens(7)); // { dozens: 0, leftover: 7 }

// Generic version:
function divideIntoGroups(total: number, groupSize: number) {
return {
fullGroups: Math.floor(total / groupSize),
remainder: total % groupSize
};
}

console.log(divideIntoGroups(50, 12)); // Same as calculateDozens(50)


8. Factorial Calculator​

  • Create a function that calculates the factorial of a number.
  • Factorial of n is: n × (n-1) × (n-2) × ... × 1
  • Calculate 5! (which is 5 × 4 × 3 × 2 × 1 = 120).
💡 Show Answer
function factorial(n: number): number {
let result: number = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}

console.log(factorial(5)); // 120
console.log(factorial(0)); // 1 (by definition)
console.log(factorial(10)); // 3628800

// Step by step for n=5:
// i=1: result = 1 * 1 = 1
// i=2: result = 1 * 2 = 2
// i=3: result = 2 * 3 = 6
// i=4: result = 6 * 4 = 24
// i=5: result = 24 * 5 = 120

// Recursive version (we'll learn more about recursion later):
function factorialRecursive(n: number): number {
if (n <= 1) return 1;
return n * factorialRecursive(n - 1);
}

console.log(factorialRecursive(5)); // 120

9. Dice Roller​

  • Create a function that simulates rolling a six-sided die.
  • It should return a random number between 1 and 6 (inclusive).
  • Roll the die 5 times and print each result.
💡 Show Answer
function rollDice(): number {
return Math.floor(Math.random() * 6) + 1;
}

// Roll 5 times:
for (let i = 1; i <= 5; i++) {
console.log(`Roll ${i}: ${rollDice()}`);
}

// Understanding the formula:
// Math.random() gives 0 to 0.999...
// Math.random() * 6 gives 0 to 5.999...
// Math.floor() makes it 0 to 5
// Adding 1 makes it 1 to 6

// Generic function for any-sided die:
function rollDie(sides: number): number {
return Math.floor(Math.random() * sides) + 1;
}

console.log(rollDie(6)); // 1-6 (standard die)
console.log(rollDie(20)); // 1-20 (D&D die)
console.log(rollDie(100)); // 1-100

// Roll two dice:
function rollTwoDice(): { die1: number; die2: number; total: number } {
const die1 = rollDice();
const die2 = rollDice();
return { die1, die2, total: die1 + die2 };
}

console.log(rollTwoDice()); // e.g., { die1: 4, die2: 3, total: 7 }


10. Compound Interest Calculator​

  • Write a function that calculates compound interest.
  • Formula: A = P(1 + r)ⁿ where:
    • A = final amount
    • P = principal (starting amount)
    • r = interest rate (as decimal)
    • n = number of years
  • Calculate the value of $1,000 invested at 5% for 10 years.
💡 Show Answer
function compoundInterest(
principal: number,
rate: number,
years: number
): number {
return principal * (1 + rate) ** years;
}

const investment = compoundInterest(1000, 0.05, 10);
console.log(investment.toFixed(2)); // 1628.89

// Compare different scenarios:
console.log(`$1,000 at 5% for 10 years: $${compoundInterest(1000, 0.05, 10).toFixed(2)}`);
console.log(`$1,000 at 7% for 10 years: $${compoundInterest(1000, 0.07, 10).toFixed(2)}`);
console.log(`$5,000 at 5% for 20 years: $${compoundInterest(5000, 0.05, 20).toFixed(2)}`);

// Enhanced version with monthly compounding:
function compoundInterestMonthly(
principal: number,
annualRate: number,
years: number
): number {
const monthlyRate = annualRate / 12;
const months = years * 12;
return principal * (1 + monthlyRate) ** months;
}

console.log(compoundInterestMonthly(1000, 0.05, 10).toFixed(2)); // 1647.01
// Monthly compounding earns slightly more!

// Calculate interest earned:
function calculateInterestEarned(
principal: number,
rate: number,
years: number
): number {
const total = compoundInterest(principal, rate, years);
return total - principal;
}

console.log(`Interest earned: $${calculateInterestEarned(1000, 0.05, 10).toFixed(2)}`);
// Interest earned: $628.89

Summary​

In this chapter, you learned:

✅ How to perform basic arithmetic operations in TypeScript

✅ The difference between operators like / (division) and % (remainder)

✅ How to use the exponentiation operator **

✅ Understanding increment ++ and decrement -- operators

✅ Compound assignment operators for cleaner code

✅ How TypeScript's type system prevents mathematical errors

✅ Important Math object methods for common calculations

✅ Building real-world calculators and converters

Key Takeaways:

  • TypeScript catches type mismatches at compile-time, preventing bugs
  • The number type covers both integers and decimals
  • Use compound assignment operators (+=, -=, etc.) for concise code
  • The Math object provides useful utilities like Math.floor(), Math.random(), etc.
  • Operator precedence matters - use parentheses when in doubt!

In the next chapter, we'll explore Logical Operators and how to make decisions in your code using boolean logic.

Continue to Chapter 3: Logical Operators →