javascript-today

Numerical Operators

Numerical operators perform mathematical calculations on numbers. Understanding these operators and how they work together is essential for any programming task involving math.

Arithmetic Operators

JavaScript provides standard arithmetic operators for mathematical operations:

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 15 / 3 5
% Modulus (remainder) 10 % 3 1
** Exponentiation 2 ** 3 8

Addition (+)

const a = 10;
const b = 5;
const sum = a + b;
console.log(sum);  // 15

// Works with decimals
const price1 = 19.99;
const price2 = 29.99;
console.log(price1 + price2);  // 49.98

// Adding multiple numbers
const total = 10 + 20 + 30 + 40;
console.log(total);  // 100

Watch out: + also concatenates strings!

console.log(5 + 3);      // 8 (number + number)
console.log('5' + '3');  // '53' (string + string)
console.log('5' + 3);    // '53' (string + number = string!)
console.log(5 + '3');    // '53' (number + string = string!)

Subtraction (-)

const a = 10;
const b = 3;
const difference = a - b;
console.log(difference);  // 7

// Works with decimals
const price = 100;
const discount = 15.50;
console.log(price - discount);  // 84.5

// Can produce negative numbers
console.log(5 - 10);  // -5

// Multiple subtractions (left to right)
console.log(100 - 20 - 10);  // 70

Multiplication (*)

const price = 29.99;
const quantity = 3;
const total = price * quantity;
console.log(total);  // 89.97

// Multiplying integers
console.log(5 * 3);  // 15

// Multiplying decimals
console.log(2.5 * 4);  // 10

// Negative numbers
console.log(-5 * 3);   // -15
console.log(-5 * -3);  // 15

Division (/)

const total = 100;
const people = 4;
const perPerson = total / people;
console.log(perPerson);  // 25

// Decimal division
console.log(10 / 3);  // 3.3333333333333335

// Be careful with zero
console.log(10 / 0);   // Infinity
console.log(-10 / 0);  // -Infinity
console.log(0 / 0);    // NaN (Not a Number)

Important: JavaScript doesn’t have integer division - division always returns a decimal (float):

console.log(5 / 2);   // 2.5 (not 2!)
console.log(10 / 4);  // 2.5 (not 2!)

// To get integer division, use Math.floor()
console.log(Math.floor(5 / 2));   // 2
console.log(Math.floor(10 / 4));  // 2

Modulus (%) - Remainder

Returns the remainder after division:

console.log(10 % 3);   // 1 (10 ÷ 3 = 3 remainder 1)
console.log(15 % 4);   // 3 (15 ÷ 4 = 3 remainder 3)
console.log(20 % 5);   // 0 (20 ÷ 5 = 4 remainder 0)

// Negative numbers
console.log(-10 % 3);  // -1
console.log(10 % -3);  // 1

Common Uses for Modulus

1. Check if number is even or odd:

const num = 7;

if (num % 2 === 0) {
  console.log('Even');
} else {
  console.log('Odd');  // This runs
}

2. Cycle through values (wrap around):

const items = ['red', 'green', 'blue'];
let index = 0;

for (let i = 0; i < 10; i++) {
  console.log(items[index % items.length]);
  index++;
}
// Output: red, green, blue, red, green, blue, red, green, blue, red

3. Get last N digits:

const number = 123456;
const lastTwoDigits = number % 100;
console.log(lastTwoDigits);  // 56

Exponentiation (**) - Power

Raises a number to a power:

console.log(2 ** 3);   // 8 (2 × 2 × 2)
console.log(5 ** 2);   // 25 (5 × 5)
console.log(10 ** 3);  // 1000 (10 × 10 × 10)

// Fractional exponents (roots)
console.log(9 ** 0.5);   // 3 (square root of 9)
console.log(8 ** (1/3)); // 2 (cube root of 8)

// Negative exponents
console.log(2 ** -1);  // 0.5 (1 / 2)
console.log(10 ** -2); // 0.01 (1 / 100)

Alternative: Use Math.pow():

console.log(Math.pow(2, 3));  // 8 (same as 2 ** 3)
console.log(2 ** 3);          // 8 (newer, cleaner syntax)

Increment (++) and Decrement (–)

Shortcuts for adding or subtracting 1:

Postfix (variable++)

Returns value, then increments:

let count = 5;
console.log(count++);  // 5 (returns old value)
console.log(count);    // 6 (now incremented)

Prefix (++variable)

Increments, then returns value:

let count = 5;
console.log(++count);  // 6 (increments first, then returns)
console.log(count);    // 6

Decrement Works the Same

let count = 10;
console.log(count--);  // 10 (postfix)
console.log(count);    // 9

count = 10;
console.log(--count);  // 9 (prefix)
console.log(count);    // 9

Common Uses

// Loop counters
for (let i = 0; i < 5; i++) {
  console.log(i);  // 0, 1, 2, 3, 4
}

// Counting down
let countdown = 5;
while (countdown > 0) {
  console.log(countdown--);  // 5, 4, 3, 2, 1
}

Assignment Operators

Combine operations with assignment:

Operator Example Equivalent to
+= x += 5 x = x + 5
-= x -= 3 x = x - 3
*= x *= 2 x = x * 2
/= x /= 4 x = x / 4
%= x %= 3 x = x % 3
**= x **= 2 x = x ** 2

Examples

let total = 100;

total += 50;   // total = 150
total -= 20;   // total = 130
total *= 2;    // total = 260
total /= 4;    // total = 65
total %= 10;   // total = 5

console.log(total);  // 5

Practical Example: Running Total

let sum = 0;

sum += 10;  // sum = 10
sum += 20;  // sum = 30
sum += 30;  // sum = 60

console.log(sum);  // 60

Operator Precedence

When multiple operators are used, precedence determines evaluation order:

Precedence Operator Description
1 (highest) () Grouping
2 ** Exponentiation
3 *, /, % Multiplication, Division, Modulus
4 +, - Addition, Subtraction
5 (lowest) =, +=, -=, etc. Assignment

Examples

// Multiplication before addition
console.log(2 + 3 * 4);    // 14 (not 20)
// Calculated as: 2 + (3 * 4) = 2 + 12 = 14

// Exponentiation before multiplication
console.log(2 * 3 ** 2);   // 18 (not 36)
// Calculated as: 2 * (3 ** 2) = 2 * 9 = 18

// Left to right for same precedence
console.log(10 - 5 + 2);   // 7 (not 3)
// Calculated as: (10 - 5) + 2 = 5 + 2 = 7

console.log(100 / 10 * 2); // 20 (not 5)
// Calculated as: (100 / 10) * 2 = 10 * 2 = 20

Use Parentheses for Clarity

// Unclear
const result = 10 + 5 * 2 - 3;

// Clear
const result = 10 + (5 * 2) - 3;  // 17

// Force different order
const result = (10 + 5) * (2 - 3);  // -15

Common Calculations

1. Average

const num1 = 85;
const num2 = 92;
const num3 = 78;

const average = (num1 + num2 + num3) / 3;
console.log(average);  // 85

2. Percentage

const score = 85;
const total = 100;

const percentage = (score / total) * 100;
console.log(percentage + '%');  // 85%

3. Calculate Discount

const price = 100;
const discountPercent = 20;

const discount = price * (discountPercent / 100);
const finalPrice = price - discount;

console.log(`Original: $${price}`);      // Original: $100
console.log(`Discount: $${discount}`);   // Discount: $20
console.log(`Final: $${finalPrice}`);    // Final: $80

4. Area and Perimeter

const length = 10;
const width = 5;

const area = length * width;
const perimeter = 2 * (length + width);

console.log(`Area: ${area}`);          // Area: 50
console.log(`Perimeter: ${perimeter}`); // Perimeter: 30

5. Temperature Conversion

// Celsius to Fahrenheit
const celsius = 25;
const fahrenheit = (celsius * 9/5) + 32;
console.log(`${celsius}°C = ${fahrenheit}°F`);  // 25°C = 77°F

// Fahrenheit to Celsius
const f = 77;
const c = (f - 32) * 5/9;
console.log(`${f}°F = ${c}°C`);  // 77°F = 25°C

Floating Point Precision Issues

JavaScript uses floating point arithmetic, which can cause precision errors:

console.log(0.1 + 0.2);        // 0.30000000000000004 (not exactly 0.3!)
console.log(0.3 - 0.1);        // 0.19999999999999998
console.log(0.1 + 0.1 + 0.1);  // 0.30000000000000004

Solutions

1. Round to fixed decimal places:

const result = 0.1 + 0.2;
console.log(result.toFixed(2));  // "0.30" (string)
console.log(parseFloat(result.toFixed(2)));  // 0.3 (number)

2. Work in cents (for money):

// Bad - floating point errors
const price1 = 0.1;
const price2 = 0.2;
console.log(price1 + price2);  // 0.30000000000000004

// Good - use cents (integers)
const price1 = 10;  // 10 cents
const price2 = 20;  // 20 cents
const total = price1 + price2;  // 30 cents
console.log(total / 100);  // 0.3 dollars

3. Use epsilon for comparisons:

function areEqual(a, b) {
  return Math.abs(a - b) < Number.EPSILON;
}

console.log(0.1 + 0.2 === 0.3);           // false
console.log(areEqual(0.1 + 0.2, 0.3));   // true

Best Practices

DO:

// Use parentheses for clarity
const result = (a + b) * (c - d);

// Round money to 2 decimal places
const price = (subtotal * taxRate).toFixed(2);

// Check for division by zero
if (divisor !== 0) {
  const result = dividend / divisor;
}

// Use const for unchanging calculations
const PI = 3.14159;
const area = PI * radius ** 2;

// Use descriptive names
const taxAmount = subtotal * taxRate;
const totalWithTax = subtotal + taxAmount;

DON’T:

// Don't rely on operator precedence - use parentheses
const unclear = 10 + 5 * 2 - 3 / 4;

// Don't compare floats with ===
if (0.1 + 0.2 === 0.3) {  // This is false!
  // Won't run
}

// Don't use division without checking for zero
const result = total / 0;  // Infinity!

// Don't do complex calculations in one line
const x = (a + b * c - d / e ** f % g) + (h - i * j);  // Hard to read

Common Mistakes

1. String Concatenation vs Addition

// ❌ Unexpected concatenation
console.log('5' + 3);   // '53' (string)
console.log(5 + '3');   // '53' (string)

// ✅ Convert to number first
console.log(Number('5') + 3);  // 8
console.log(5 + Number('3'));  // 8
console.log(parseInt('5') + 3); // 8

2. Increment/Decrement Confusion

let x = 5;

// ❌ Confusing post-increment
const y = x++;  // y = 5, x = 6

// ✅ Clearer
const y = x;
x = x + 1;

3. Modulus with Negative Numbers

console.log(-10 % 3);   // -1 (not 2!)
console.log(10 % -3);   // 1 (not -2!)

// For positive modulo, use this function:
function mod(n, m) {
  return ((n % m) + m) % m;
}
console.log(mod(-10, 3));  // 2

Summary

Basic Operators:

  • + Addition (watch out for string concatenation!)
  • - Subtraction
  • * Multiplication
  • / Division (always returns decimal)
  • % Modulus (remainder)
  • ** Exponentiation (power)

Shortcuts:

  • ++ Increment by 1
  • -- Decrement by 1
  • +=, -=, *=, /=, %=, **= Compound assignment

Precedence (high to low):

  1. () Parentheses
  2. ** Exponentiation
  3. *, /, % Multiplication, Division, Modulus
  4. +, - Addition, Subtraction

Remember:

  • Use parentheses for clarity
  • Division by zero = Infinity
  • Floating point math has precision issues
  • + with strings = concatenation