JavaScript Tutorial

JavaScript Arithmetic Operators: Complete Guide with Examples

Master JavaScript arithmetic operators including addition, subtraction, multiplication, division, modulus, exponentiation, increment, and decrement. Learn with practical examples and best practices.

Welcome back! πŸ‘‹ In the previous lesson, you learned about operators and expressions in general. Now, let's dive deep into arithmetic operators - the operators you'll use to perform mathematical calculations in JavaScript.

Arithmetic operators are essential for any program that needs to work with numbers, whether you're building a calculator, calculating prices, or processing data.


What are Arithmetic Operators?

Arithmetic operators perform mathematical operations on numeric values (operands) and return a single numeric value.

JavaScript provides several arithmetic operators that work similar to basic math:

let x = 10;
let y = 3;

console.log(x + y);  // 13 - Addition
console.log(x - y);  // 7  - Subtraction
console.log(x * y);  // 30 - Multiplication
console.log(x / y);  // 3.333... - Division
console.log(x % y);  // 1  - Modulus (remainder)
console.log(x ** y); // 1000 - Exponentiation (10Β³)

Basic Arithmetic Operators

Let's explore each arithmetic operator in detail.


Addition Operator (+)

The addition operator adds two numbers together.

Syntax

operand1 + operand2

Examples

// Basic addition
console.log(5 + 3);          // 8
console.log(10 + 20);        // 30
console.log(-5 + 3);         // -2
console.log(0.1 + 0.2);      // 0.30000000000000004 (floating point issue)

// With variables
let a = 15;
let b = 25;
let sum = a + b;
console.log(sum);            // 40

// Multiple additions
console.log(1 + 2 + 3 + 4);  // 10

// Adding negative numbers
console.log(10 + (-5));      // 5
console.log(-10 + (-5));     // -15

Addition with Different Types (Type Coercion)

Important: The + operator behaves differently when used with strings!

// Number + Number = Number (addition)
console.log(5 + 3);          // 8

// String + Number = String (concatenation!)
console.log("5" + 3);        // "53"
console.log(5 + "3");        // "53"

// String + String = String (concatenation)
console.log("Hello" + " World");  // "Hello World"

// Mixed operations (left to right evaluation)
console.log(5 + 3 + "2");    // "82" (5+3=8, then "8"+"2"="82")
console.log("2" + 5 + 3);    // "253" ("2"+5="25", then "25"+3="253")

// Be careful with type conversion!
let price = 100;
let userInput = "50";        // String from user input
console.log(price + userInput);     // "10050" (concatenation, not addition!)
console.log(price + Number(userInput)); // 150 (correct addition)

Practical Examples

// Calculate total price
let itemPrice = 29.99;
let quantity = 3;
let total = itemPrice * quantity;
console.log(`Total: $${total}`); // Total: $89.97

// Calculate sum of array elements
let numbers = [10, 20, 30, 40];
let sum = numbers[0] + numbers[1] + numbers[2] + numbers[3];
console.log(`Sum: ${sum}`); // Sum: 100

// Adding time (minutes and seconds to total seconds)
let minutes = 5;
let seconds = 30;
let totalSeconds = (minutes * 60) + seconds;
console.log(`Total seconds: ${totalSeconds}`); // Total seconds: 330

Subtraction Operator (-)

The subtraction operator subtracts the second number from the first.

Syntax

operand1 - operand2

Examples

// Basic subtraction
console.log(10 - 3);         // 7
console.log(5 - 8);          // -3
console.log(0 - 5);          // -5
console.log(-5 - 3);         // -8

// With variables
let balance = 1000;
let expense = 250;
let remaining = balance - expense;
console.log(remaining);      // 750

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

// Subtracting negative numbers
console.log(10 - (-5));      // 15 (equivalent to 10 + 5)
console.log(-10 - (-5));     // -5 (equivalent to -10 + 5)

Subtraction with Type Coercion

Unlike +, the - operator always tries to convert operands to numbers:

// String - Number = Number (converts string to number)
console.log("10" - 3);       // 7
console.log("5" - "2");      // 3
console.log(10 - "3");       // 7

// Invalid conversions result in NaN
console.log("hello" - 5);    // NaN
console.log("10" - "abc");   // NaN

// With boolean (true = 1, false = 0)
console.log(10 - true);      // 9
console.log(10 - false);     // 10

// With null and undefined
console.log(10 - null);      // 10 (null becomes 0)
console.log(10 - undefined); // NaN (undefined becomes NaN)

Practical Examples

// Calculate change
let paymentAmount = 100;
let purchaseAmount = 67.50;
let change = paymentAmount - purchaseAmount;
console.log(`Change: $${change.toFixed(2)}`); // Change: $32.50

// Calculate age difference
let myAge = 30;
let friendAge = 25;
let ageDifference = myAge - friendAge;
console.log(`Age difference: ${ageDifference} years`); // Age difference: 5 years

// Calculate discount
let originalPrice = 200;
let discount = 40;
let finalPrice = originalPrice - discount;
console.log(`Final price: $${finalPrice}`); // Final price: $160

Multiplication Operator (*)

The multiplication operator multiplies two numbers.

Syntax

operand1 * operand2

Examples

// Basic multiplication
console.log(5 * 3);          // 15
console.log(10 * 4);         // 40
console.log(-5 * 3);         // -15
console.log(-5 * -3);        // 15

// With variables
let price = 25;
let quantity = 4;
let total = price * quantity;
console.log(total);          // 100

// Multiple multiplications
console.log(2 * 3 * 4);      // 24

// With decimals
console.log(2.5 * 4);        // 10
console.log(0.1 * 0.2);      // 0.020000000000000004 (floating point)

Multiplication with Type Coercion

The * operator converts operands to numbers:

// String * Number = Number
console.log("5" * 3);        // 15
console.log("10" * "2");     // 20
console.log(5 * "3");        // 15

// Invalid conversions result in NaN
console.log("hello" * 5);    // NaN
console.log("10" * "abc");   // NaN

// With boolean (true = 1, false = 0)
console.log(5 * true);       // 5
console.log(5 * false);      // 0

// With null and undefined
console.log(5 * null);       // 0 (null becomes 0)
console.log(5 * undefined);  // NaN

Practical Examples

// Calculate area
let length = 10;
let width = 5;
let area = length * width;
console.log(`Area: ${area} square units`); // Area: 50 square units

// Calculate total cost with tax
let itemPrice = 100;
let taxRate = 0.08;
let taxAmount = itemPrice * taxRate;
let totalWithTax = itemPrice + taxAmount;
console.log(`Total with tax: $${totalWithTax}`); // Total with tax: $108

// Convert hours to minutes
let hours = 3;
let minutes = hours * 60;
console.log(`${hours} hours = ${minutes} minutes`); // 3 hours = 180 minutes

// Calculate grid cells
let rows = 10;
let columns = 8;
let totalCells = rows * columns;
console.log(`Total cells: ${totalCells}`); // Total cells: 80

Division Operator (/)

The division operator divides the first number by the second.

Syntax

operand1 / operand2

Examples

// Basic division
console.log(10 / 2);         // 5
console.log(15 / 3);         // 5
console.log(7 / 2);          // 3.5 (JavaScript keeps decimals!)
console.log(10 / 3);         // 3.3333333333333335

// With variables
let total = 100;
let parts = 4;
let perPart = total / parts;
console.log(perPart);        // 25

// Negative division
console.log(-10 / 2);        // -5
console.log(10 / -2);        // -5
console.log(-10 / -2);       // 5

Division by Zero

Important: JavaScript handles division by zero differently than many languages:

// Division by zero
console.log(10 / 0);         // Infinity
console.log(-10 / 0);        // -Infinity
console.log(0 / 0);          // NaN

// Check for Infinity
let result = 10 / 0;
console.log(isFinite(result)); // false
console.log(result === Infinity); // true

Division with Type Coercion

// String / Number = Number
console.log("10" / 2);       // 5
console.log("20" / "4");     // 5
console.log(10 / "2");       // 5

// Invalid conversions result in NaN
console.log("hello" / 5);    // NaN
console.log("10" / "abc");   // NaN

// With boolean
console.log(10 / true);      // 10 (true = 1)
console.log(10 / false);     // Infinity (division by 0!)

// With null and undefined
console.log(10 / null);      // Infinity (null becomes 0)
console.log(10 / undefined); // NaN

Practical Examples

// Calculate average
let sum = 150;
let count = 5;
let average = sum / count;
console.log(`Average: ${average}`); // Average: 30

// Split bill
let totalBill = 120;
let people = 4;
let perPerson = totalBill / people;
console.log(`Per person: $${perPerson}`); // Per person: $30

// Calculate unit price
let packagePrice = 25.99;
let units = 6;
let unitPrice = packagePrice / units;
console.log(`Unit price: $${unitPrice.toFixed(2)}`); // Unit price: $4.33

// Convert minutes to hours
let totalMinutes = 150;
let totalHours = totalMinutes / 60;
console.log(`${totalMinutes} minutes = ${totalHours} hours`); // 150 minutes = 2.5 hours

Modulus Operator (%)

The modulus operator returns the remainder after division. It's also called the remainder operator.

Syntax

operand1 % operand2

Examples

// Basic modulus
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)
console.log(7 % 2);          // 1 (odd number)
console.log(8 % 2);          // 0 (even number)

// With variables
let total = 17;
let groupSize = 5;
let leftover = total % groupSize;
console.log(`Leftover: ${leftover}`); // Leftover: 2

// With negative numbers
console.log(-10 % 3);        // -1 (sign of dividend)
console.log(10 % -3);        // 1 (sign of dividend)
console.log(-10 % -3);       // -1

Common Use Cases for Modulus

1. Check if number is even or odd:

function isEven(num) {
  return num % 2 === 0;
}

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

function isOdd(num) {
  return num % 2 !== 0;
}

console.log(isOdd(10));      // false
console.log(isOdd(7));       // true

2. Check if number is divisible by another:

function isDivisibleBy(num, divisor) {
  return num % divisor === 0;
}

console.log(isDivisibleBy(15, 5));  // true (15 is divisible by 5)
console.log(isDivisibleBy(15, 4));  // false (15 is not divisible by 4)

3. Cycle through values (wrap around):

// Cycle through days of week (0-6)
let dayNumber = 10;
let dayOfWeek = dayNumber % 7;
console.log(dayOfWeek);      // 3 (wraps around)

// Cycle through array indices
let colors = ["red", "green", "blue"];
let index = 5;
let color = colors[index % colors.length];
console.log(color);          // "green" (5 % 3 = 2, colors[2])

4. Get last digits of a number:

let number = 12345;
let lastDigit = number % 10;
console.log(lastDigit);      // 5

let lastTwoDigits = number % 100;
console.log(lastTwoDigits);  // 45

5. Distribute items evenly:

let items = 17;
let containers = 5;
let itemsPerContainer = Math.floor(items / containers);
let remainingItems = items % containers;

console.log(`Items per container: ${itemsPerContainer}`); // 3
console.log(`Remaining items: ${remainingItems}`);        // 2

Modulus with Type Coercion

// String % Number = Number
console.log("10" % 3);       // 1
console.log("15" % "4");     // 3

// Invalid conversions result in NaN
console.log("hello" % 5);    // NaN

// With boolean
console.log(10 % true);      // 0 (true = 1)
console.log(10 % false);     // NaN (division by 0)

Practical Examples

// Check if year is leap year (simplified)
function isLeapYear(year) {
  return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

console.log(isLeapYear(2024)); // true
console.log(isLeapYear(2023)); // false
console.log(isLeapYear(2000)); // true
console.log(isLeapYear(1900)); // false

// Format time (convert seconds to MM:SS)
function formatTime(totalSeconds) {
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}

console.log(formatTime(125));  // "2:05"
console.log(formatTime(90));   // "1:30"
console.log(formatTime(45));   // "0:45"

// Pagination (get page number)
function getPageNumber(itemIndex, itemsPerPage) {
  return Math.floor(itemIndex / itemsPerPage) + 1;
}

console.log(getPageNumber(0, 10));   // Page 1
console.log(getPageNumber(15, 10));  // Page 2
console.log(getPageNumber(25, 10));  // Page 3

Exponentiation Operator (**)

The exponentiation operator raises the first operand to the power of the second operand. It was introduced in ES2016 (ES7).

Syntax

operand1 ** operand2

This is equivalent to: Math.pow(operand1, operand2)

Examples

// Basic exponentiation
console.log(2 ** 3);         // 8 (2Β³ = 2 Γ— 2 Γ— 2)
console.log(5 ** 2);         // 25 (5Β² = 5 Γ— 5)
console.log(10 ** 3);        // 1000 (10Β³)
console.log(4 ** 0.5);       // 2 (square root of 4)

// With variables
let base = 3;
let exponent = 4;
let result = base ** exponent;
console.log(result);         // 81 (3⁴)

// Negative exponents (fraction/decimal)
console.log(2 ** -1);        // 0.5 (2⁻¹ = 1/2)
console.log(2 ** -2);        // 0.25 (2⁻² = 1/4)
console.log(10 ** -3);       // 0.001 (10⁻³)

// Decimal exponents (roots)
console.log(9 ** 0.5);       // 3 (square root)
console.log(27 ** (1/3));    // 3 (cube root)
console.log(16 ** 0.25);     // 2 (fourth root)

Exponentiation vs Math.pow()

// Both are equivalent
console.log(2 ** 3);         // 8
console.log(Math.pow(2, 3)); // 8

// ** operator is more concise
let result1 = 5 ** 2;
let result2 = Math.pow(5, 2);

Right-to-Left Associativity

Important: Exponentiation is right-associative (unlike other operators):

// Right-to-left evaluation
console.log(2 ** 3 ** 2);    // 512
// Evaluated as: 2 ** (3 ** 2) = 2 ** 9 = 512
// NOT: (2 ** 3) ** 2 = 8 ** 2 = 64

// To change order, use parentheses
console.log((2 ** 3) ** 2);  // 64

Exponentiation with Type Coercion

// String ** Number = Number
console.log("2" ** 3);       // 8
console.log("5" ** "2");     // 25

// Invalid conversions result in NaN
console.log("hello" ** 2);   // NaN

// With boolean
console.log(2 ** true);      // 2 (true = 1)
console.log(2 ** false);     // 1 (2⁰ = 1)

Practical Examples

// Calculate compound interest
function calculateCompoundInterest(principal, rate, time) {
  return principal * (1 + rate) ** time;
}

let principal = 1000;
let rate = 0.05;      // 5% per year
let years = 3;
let finalAmount = calculateCompoundInterest(principal, rate, years);
console.log(`Final amount: $${finalAmount.toFixed(2)}`); // Final amount: $1157.63

// Calculate area of circle
function circleArea(radius) {
  return Math.PI * radius ** 2;
}

console.log(circleArea(5).toFixed(2));  // 78.54

// Scientific notation
let distance = 3 * (10 ** 8); // Speed of light in m/s
console.log(distance);         // 300000000

// Calculate volume of cube
function cubeVolume(side) {
  return side ** 3;
}

console.log(cubeVolume(4));    // 64

// Population growth
function populationGrowth(initial, growthRate, years) {
  return initial * (1 + growthRate) ** years;
}

console.log(populationGrowth(1000000, 0.02, 10).toFixed(0)); // 1218994

Unary Arithmetic Operators

Unary operators work with a single operand.


Unary Plus (+)

Converts its operand to a number.

Syntax

+operand

Examples

// Converting strings to numbers
console.log(+"5");           // 5
console.log(+"3.14");        // 3.14
console.log(+"-10");         // -10

// Already a number (no change)
console.log(+42);            // 42

// With boolean
console.log(+true);          // 1
console.log(+false);         // 0

// With null and undefined
console.log(+null);          // 0
console.log(+undefined);     // NaN

// Invalid conversions
console.log(+"hello");       // NaN
console.log(+"123abc");      // NaN

Practical Use

// Quick type conversion
let userInput = "25";
let age = +userInput;        // Convert to number
console.log(typeof age);     // "number"

// In expressions
let price = "100";
let tax = +"8";
let total = +price + tax;
console.log(total);          // 108

// Alternative to Number()
console.log(Number("42"));   // 42
console.log(+"42");          // 42 (shorter)

Unary Negation (-)

Converts its operand to a number and negates it.

Syntax

-operand

Examples

// Negating numbers
console.log(-5);             // -5
console.log(-(-5));          // 5 (double negation)
console.log(-(10));          // -10

// Converting and negating strings
console.log(-"5");           // -5
console.log(-"3.14");        // -3.14

// With boolean
console.log(-true);          // -1
console.log(-false);         // -0

// With null and undefined
console.log(-null);          // -0
console.log(-undefined);     // NaN

// Invalid conversions
console.log(-"hello");       // NaN

Practical Examples

// Toggle sign
let temperature = 25;
let opposite = -temperature;
console.log(opposite);       // -25

// Calculate debt
let balance = 100;
let debt = -balance;
console.log(debt);           // -100

// Converting string to negative number
let userInput = "50";
let deduction = -userInput;
console.log(deduction);      // -50

Increment and Decrement Operators

These operators increase or decrease a number by 1. They're commonly used in loops and counters.


Increment Operator (++)

Increases a number by 1.

Two Forms: Prefix and Postfix

Prefix Increment (++variable):

  • Increments first
  • Returns new value

Postfix Increment (variable++):

  • Returns old value
  • Increments after

Examples

Prefix Increment:

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

// Breakdown:
// 1. x becomes 6
// 2. Returns 6

Postfix Increment:

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

// Breakdown:
// 1. Returns 5
// 2. y becomes 6

Side-by-Side Comparison

// Prefix
let a = 10;
let b = ++a;
console.log(a);    // 11
console.log(b);    // 11 (got incremented value)

// Postfix
let x = 10;
let y = x++;
console.log(x);    // 11
console.log(y);    // 10 (got original value)

In Expressions

// Prefix
let count = 5;
let result = ++count + 10;
console.log(result);   // 16 (count becomes 6, then 6 + 10)
console.log(count);    // 6

// Postfix
let count2 = 5;
let result2 = count2++ + 10;
console.log(result2);  // 15 (5 + 10, then count becomes 6)
console.log(count2);   // 6

Common Use in Loops

// Most common use: for loops
for (let i = 0; i < 5; i++) {
  console.log(i);  // 0, 1, 2, 3, 4
}

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

// In for loops, prefix vs postfix makes no difference

Practical Examples

// Counter
let visitors = 0;
visitors++;           // Increment by 1
console.log(visitors); // 1

// Array index
let fruits = ["apple", "banana", "orange"];
let index = 0;
console.log(fruits[index++]); // "apple" (then index becomes 1)
console.log(fruits[index++]); // "banana" (then index becomes 2)
console.log(fruits[index++]); // "orange" (then index becomes 3)

// While loop
let countdown = 3;
while (countdown > 0) {
  console.log(countdown);
  countdown--;  // Could also use --countdown
}
// Output: 3, 2, 1

Decrement Operator (--)

Decreases a number by 1.

Two Forms: Prefix and Postfix

Prefix Decrement (--variable):

  • Decrements first
  • Returns new value

Postfix Decrement (variable--):

  • Returns old value
  • Decrements after

Examples

Prefix Decrement:

let x = 5;
console.log(--x);  // 4 (decrements first, then returns)
console.log(x);    // 4

Postfix Decrement:

let y = 5;
console.log(y--);  // 5 (returns first, then decrements)
console.log(y);    // 4

Side-by-Side Comparison

// Prefix
let a = 10;
let b = --a;
console.log(a);    // 9
console.log(b);    // 9 (got decremented value)

// Postfix
let x = 10;
let y = x--;
console.log(x);    // 9
console.log(y);    // 10 (got original value)

Practical Examples

// Countdown timer
let timeLeft = 10;
while (timeLeft > 0) {
  console.log(timeLeft);
  timeLeft--;
}
console.log("Time's up!");

// Lives in a game
let lives = 3;
console.log(`Lives: ${lives}`);  // Lives: 3
lives--;
console.log(`Lives: ${lives}`);  // Lives: 2
lives--;
console.log(`Lives: ${lives}`);  // Lives: 1

// Stack operations (pop)
let stack = [1, 2, 3, 4, 5];
let top = stack.length - 1;
console.log(stack[top--]);  // 5
console.log(stack[top--]);  // 4
console.log(stack[top--]);  // 3

Operator Precedence with Arithmetic Operators

Understanding the order of operations is crucial for writing correct expressions.

Precedence Rules (High to Low)

// 1. Parentheses ()
// 2. Exponentiation **
// 3. Prefix increment/decrement ++ --
// 4. Unary + -
// 5. Multiplication, Division, Modulus * / %
// 6. Addition, Subtraction + -
// 7. Postfix increment/decrement ++ --

Examples

// Example 1: Multiplication before addition
let result = 5 + 3 * 2;
console.log(result);  // 11 (not 16!)
// Evaluated as: 5 + (3 * 2) = 5 + 6 = 11

// Example 2: Exponentiation before multiplication
let result2 = 2 * 3 ** 2;
console.log(result2);  // 18 (not 36!)
// Evaluated as: 2 * (3 ** 2) = 2 * 9 = 18

// Example 3: Division before subtraction
let result3 = 10 - 6 / 2;
console.log(result3);  // 7 (not 2!)
// Evaluated as: 10 - (6 / 2) = 10 - 3 = 7

// Example 4: Complex expression
let result4 = 2 + 3 * 4 ** 2 / 2 - 1;
// Step by step:
// 1. 4 ** 2 = 16
// 2. 3 * 16 = 48
// 3. 48 / 2 = 24
// 4. 2 + 24 = 26
// 5. 26 - 1 = 25
console.log(result4);  // 25

Using Parentheses for Clarity

// Without parentheses (confusing)
let total1 = 10 + 5 * 2;  // 20 - but is this what you meant?

// With parentheses (clear)
let total2 = (10 + 5) * 2;  // 30 - explicitly left to right
let total3 = 10 + (5 * 2);  // 20 - explicitly multiplication first

// Complex calculation with parentheses
let price = 100;
let quantity = 3;
let discount = 0.1;
let tax = 0.08;

// Bad - hard to understand
let total4 = price * quantity - price * quantity * discount + price * quantity * (1 - discount) * tax;

// Good - broken down with parentheses
let subtotal = price * quantity;
let discountAmount = subtotal * discount;
let afterDiscount = subtotal - discountAmount;
let taxAmount = afterDiscount * tax;
let total5 = afterDiscount + taxAmount;

// Or with clear parentheses in one expression
let total6 = (price * quantity) * (1 - discount) * (1 + tax);

Common Mistakes and Pitfalls

Mistake 1: Confusing + with Concatenation

// ❌ Problem
let price = "100";
let tax = 10;
console.log(price + tax);  // "10010" (concatenation!)

// βœ… Solution
console.log(Number(price) + tax);  // 110
console.log(+price + tax);         // 110

Mistake 2: Floating Point Precision

// ❌ Problem
console.log(0.1 + 0.2);  // 0.30000000000000004 (not exactly 0.3!)

// βœ… Solution - round to fixed decimals
let result = 0.1 + 0.2;
console.log(result.toFixed(2));  // "0.30"
console.log(Number(result.toFixed(2)));  // 0.3

// βœ… Better - work with integers
let cents1 = 10;  // $0.10
let cents2 = 20;  // $0.20
let totalCents = cents1 + cents2;
let dollars = totalCents / 100;
console.log(dollars);  // 0.3

Mistake 3: Division by Zero

// ❌ Problem - doesn't throw error, returns Infinity
let result = 10 / 0;
console.log(result);  // Infinity

// βœ… Solution - check before dividing
function safeDivide(a, b) {
  if (b === 0) {
    return null;  // or throw error
  }
  return a / b;
}

console.log(safeDivide(10, 2));  // 5
console.log(safeDivide(10, 0));  // null

Mistake 4: Incorrect Increment Usage

// ❌ Problem - using wrong form
let x = 5;
let y = x++ + x;  // Confusing!
console.log(y);   // 11 (5 + 6)

// βœ… Solution - be explicit
let a = 5;
let b = a;
a++;
let c = b + a;
console.log(c);   // 11 (much clearer!)

Mistake 5: Modulus with Negative Numbers

// Be aware of sign behavior
console.log(10 % 3);   // 1
console.log(-10 % 3);  // -1 (negative!)
console.log(10 % -3);  // 1 (positive!)

// For absolute remainder
function absModulus(a, b) {
  return Math.abs(a % b);
}

console.log(absModulus(-10, 3));  // 1

Mistake 6: Operator Precedence Confusion

// ❌ Problem
let result = 10 + 5 * 2;
console.log(result);  // 20 - but did you mean 30?

// βœ… Solution - use parentheses
let result2 = (10 + 5) * 2;
console.log(result2);  // 30 - clear intent

Best Practices

1. Use Parentheses for Clarity

// ❌ Unclear
let result = a + b * c / d;

// βœ… Clear
let result = a + ((b * c) / d);

2. Avoid Postfix/Prefix in Complex Expressions

// ❌ Confusing
let x = 5;
let y = ++x + x++ + x;

// βœ… Clear
let a = 5;
a++;
let b = a + a;
a++;
let c = b + a;

3. Handle Floating Point with Care

// ❌ Don't rely on exact decimal equality
if (0.1 + 0.2 === 0.3) {  // false!
  console.log("Equal");
}

// βœ… Use a tolerance
function areEqual(a, b, tolerance = 0.0001) {
  return Math.abs(a - b) < tolerance;
}

if (areEqual(0.1 + 0.2, 0.3)) {  // true
  console.log("Equal");
}

4. Use Meaningful Variable Names

// ❌ Bad
let x = p * q;

// βœ… Good
let totalPrice = unitPrice * quantity;

5. Break Complex Calculations into Steps

// ❌ Hard to read
let t = p * q * (1 - d) * (1 + r);

// βœ… Easy to understand
let subtotal = unitPrice * quantity;
let afterDiscount = subtotal * (1 - discountRate);
let total = afterDiscount * (1 + taxRate);

6. Validate Inputs

// ❌ No validation
function divide(a, b) {
  return a / b;
}

// βœ… With validation
function divide(a, b) {
  if (typeof a !== "number" || typeof b !== "number") {
    throw new TypeError("Both arguments must be numbers");
  }
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  if (!isFinite(a) || !isFinite(b)) {
    throw new Error("Arguments must be finite numbers");
  }
  return a / b;
}

Practical Examples

Example 1: Temperature Converter

function celsiusToFahrenheit(celsius) {
  return (celsius * 9/5) + 32;
}

function fahrenheitToCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5/9;
}

console.log(celsiusToFahrenheit(0));    // 32
console.log(celsiusToFahrenheit(100));  // 212
console.log(fahrenheitToCelsius(32));   // 0
console.log(fahrenheitToCelsius(98.6)); // 37

Example 2: Shopping Cart Calculator

function calculateCart(items) {
  let subtotal = 0;
  
  for (let item of items) {
    subtotal += item.price * item.quantity;
  }
  
  let discountRate = subtotal > 100 ? 0.1 : 0;
  let discountAmount = subtotal * discountRate;
  let afterDiscount = subtotal - discountAmount;
  
  let taxRate = 0.08;
  let taxAmount = afterDiscount * taxRate;
  
  let total = afterDiscount + taxAmount;
  
  return {
    subtotal: subtotal.toFixed(2),
    discount: discountAmount.toFixed(2),
    tax: taxAmount.toFixed(2),
    total: total.toFixed(2)
  };
}

let cart = [
  { name: "Book", price: 25.99, quantity: 2 },
  { name: "Pen", price: 5.99, quantity: 3 },
  { name: "Notebook", price: 12.99, quantity: 1 }
];

console.log(calculateCart(cart));
// {
//   subtotal: "82.94",
//   discount: "0.00",
//   tax: "6.64",
//   total: "89.58"
// }

Example 3: Loan Payment Calculator

function calculateMonthlyPayment(principal, annualRate, years) {
  let monthlyRate = annualRate / 12 / 100;
  let months = years * 12;
  
  if (monthlyRate === 0) {
    return principal / months;
  }
  
  let payment = principal * 
    (monthlyRate * (1 + monthlyRate) ** months) / 
    ((1 + monthlyRate) ** months - 1);
  
  return payment.toFixed(2);
}

console.log(calculateMonthlyPayment(200000, 4.5, 30));
// "1013.37" (monthly payment for $200k loan at 4.5% for 30 years)

Example 4: BMI Calculator

function calculateBMI(weight, height) {
  // weight in kg, height in meters
  let bmi = weight / (height ** 2);
  
  let category;
  if (bmi < 18.5) {
    category = "Underweight";
  } else if (bmi < 25) {
    category = "Normal weight";
  } else if (bmi < 30) {
    category = "Overweight";
  } else {
    category = "Obese";
  }
  
  return {
    bmi: bmi.toFixed(1),
    category: category
  };
}

console.log(calculateBMI(70, 1.75));
// { bmi: "22.9", category: "Normal weight" }

Example 5: Time Calculator

function secondsToHMS(seconds) {
  let hours = Math.floor(seconds / 3600);
  let remainingSeconds = seconds % 3600;
  let minutes = Math.floor(remainingSeconds / 60);
  let secs = remainingSeconds % 60;
  
  return {
    hours: hours,
    minutes: minutes,
    seconds: secs,
    formatted: `${hours}h ${minutes}m ${secs}s`
  };
}

console.log(secondsToHMS(7384));
// { hours: 2, minutes: 3, seconds: 4, formatted: "2h 3m 4s" }

function HMSToSeconds(hours, minutes, seconds) {
  return (hours * 3600) + (minutes * 60) + seconds;
}

console.log(HMSToSeconds(2, 3, 4)); // 7384

Practice Exercises

Create a file called arithmetic-practice.js:

// Arithmetic Operators Practice

// Exercise 1: Circle Calculator
function circleCalculations(radius) {
  // Calculate:
  // - Circumference: 2 Γ— Ο€ Γ— radius
  // - Area: Ο€ Γ— radiusΒ²
  // Return object with both values
}

// Test
console.log(circleCalculations(5));
// Should return: { circumference: 31.42, area: 78.54 }

// Exercise 2: Grade Calculator
function calculateGrade(scores) {
  // Calculate average of all scores
  // Return letter grade:
  // A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: below 60
}

// Test
console.log(calculateGrade([85, 90, 78, 92, 88]));
// Should return: "B"

// Exercise 3: Compound Interest
function compoundInterest(principal, rate, time, frequency) {
  // A = P(1 + r/n)^(nt)
  // P = principal, r = annual rate, t = time in years, n = frequency
  // Return final amount
}

// Test
console.log(compoundInterest(1000, 0.05, 10, 4));
// Should return approximately: 1643.62

// Exercise 4: Split Bill with Tip
function splitBill(billAmount, tipPercent, people) {
  // Calculate:
  // - Tip amount
  // - Total with tip
  // - Amount per person
  // Return object with all values
}

// Test
console.log(splitBill(120, 18, 4));
// Should return: { tip: 21.60, total: 141.60, perPerson: 35.40 }

// Exercise 5: Is Prime Number
function isPrime(num) {
  // Check if number is prime
  // Use modulus operator to check divisibility
  // Hint: Only need to check up to square root of num
}

// Test
console.log(isPrime(17));  // true
console.log(isPrime(18));  // false
console.log(isPrime(97));  // true

Summary

Congratulations! πŸŽ‰ You now have a comprehensive understanding of arithmetic operators in JavaScript.

Key Takeaways

βœ… Basic Operators:

  • + Addition (also concatenates strings)
  • - Subtraction
  • * Multiplication
  • / Division (returns decimal)
  • % Modulus (remainder)
  • ** Exponentiation (power)

βœ… Unary Operators:

  • + Convert to number
  • - Convert and negate
  • ++ Increment by 1 (prefix/postfix)
  • -- Decrement by 1 (prefix/postfix)

βœ… Important Concepts:

  • Operator precedence (order of operations)
  • Type coercion with arithmetic operators
  • Prefix vs postfix increment/decrement
  • Floating point precision issues
  • Division by zero returns Infinity

βœ… Best Practices:

  • Use parentheses for clarity
  • Validate inputs
  • Handle floating point carefully
  • Use meaningful variable names
  • Break complex calculations into steps

What's Next?

Great job mastering arithmetic operators!

In the next lesson, we'll explore Assignment Operators where you'll learn:

  • Simple assignment (=)
  • Compound assignments (+=, -=, *=, /=, %=, **=)
  • Logical assignments (&&=, ||=, ??=)
  • Assignment patterns and best practices