JavaScript Arithmetic
Master mathematical operations in JavaScript
🧮 JavaScript Arithmetic Operators
JavaScript arithmetic operators perform mathematical operations on numbers. They work just like math in real life!
// Basic arithmetic operations
let a = 10;
let b = 3;
console.log(a + b); // Addition
console.log(a - b); // Subtraction
console.log(a * b); // Multiplication
console.log(a / b); // Division
Console Output:
13 7 30 3.3333333333333335
Arithmetic Operators
Addition (+)
Adds two numbers together
let sum = 5 + 3; // 8
Subtraction (-)
Subtracts one number from another
let diff = 10 - 4; // 6
Multiplication (*)
Multiplies two numbers
let product = 6 * 7; // 42
Division (/)
Divides one number by another
let quotient = 15 / 3; // 5
🔹 More Arithmetic Operators
JavaScript has additional arithmetic operators for special operations:
let x = 17;
let y = 5;
// Modulus (remainder)
console.log(x % y); // 2 (17 divided by 5 = 3 remainder 2)
// Exponentiation (power)
console.log(2 ** 3); // 8 (2 to the power of 3)
// Increment
let count = 5;
count++; // Same as count = count + 1
console.log(count); // 6
// Decrement
count--; // Same as count = count - 1
console.log(count); // 5
Console Output:
2 8 6 5
🔹 Order of Operations
JavaScript follows mathematical order of operations (PEMDAS):
// Without parentheses
let result1 = 2 + 3 * 4; // 14 (multiplication first)
// With parentheses
let result2 = (2 + 3) * 4; // 20 (addition first)
// Complex example
let result3 = 10 + 2 * 3 ** 2; // 10 + 2 * 9 = 10 + 18 = 28
console.log(result1, result2, result3);
Console Output:
14 20 28
🔹 Real-World Examples
Here are practical examples of arithmetic in JavaScript:
// Calculate total price with tax
let price = 29.99;
let taxRate = 0.08; // 8% tax
let total = price + (price * taxRate);
console.log("Total: $" + total.toFixed(2));
// Calculate area of a circle
let radius = 5;
let area = Math.PI * radius ** 2;
console.log("Area: " + area.toFixed(2));
// Calculate average score
let score1 = 85;
let score2 = 92;
let score3 = 78;
let average = (score1 + score2 + score3) / 3;
console.log("Average: " + average.toFixed(1));
Console Output:
Total: $32.39 Area: 78.54 Average: 85.0