Math in JavaScript

JavaScript provides comprehensive mathematical capabilities through arithmetic operators and the built-in Math object. Learn how to perform calculations, generate random numbers, and solve real-world math problems.

🧮 Basic Arithmetic Operations

JavaScript provides all standard arithmetic operators for mathematical calculations. These operators follow standard mathematical precedence rules.

JavaScript Editor
Arithmetic Operators:
  • + - Addition
  • - - Subtraction
  • * - Multiplication
  • / - Division
  • % - Modulus (remainder)
  • ** - Exponentiation (ES6)
Increment/Decrement:
  • ++x - Pre-increment (increment then return)
  • x++ - Post-increment (return then increment)
  • --x - Pre-decrement
  • x-- - Post-decrement

📊 The Math Object

JavaScript provides a built-in Math object with properties and methods for mathematical constants and functions. No need to create it - it's available globally.

JavaScript Editor
Common Methods:
  • Math.round() - Round to nearest integer
  • Math.ceil() - Round up
  • Math.floor() - Round down
  • Math.trunc() - Remove decimal part
Power & Roots:
  • Math.pow(x, y) - x to the power y
  • Math.sqrt(x) - Square root
  • Math.cbrt(x) - Cube root
Trigonometry:
  • Math.sin(x) - Sine (radians)
  • Math.cos(x) - Cosine
  • Math.tan(x) - Tangent

🎲 Random Numbers & Utilities

The Math.random() method generates pseudo-random numbers. For random integers in a specific range, we need to do some calculations.

JavaScript Editor
💡 Generating Random Integers:

Math.random() returns a decimal between 0 (inclusive) and 1 (exclusive).
To get an integer between min and max:Math.floor(Math.random() * (max - min + 1)) + min

💰 Practical Examples

Let's apply our math knowledge to solve real-world problems like price calculations, distance measurement, and currency conversion.

JavaScript Editor
📝 Try These Challenges:
  1. Modify the discount calculator to apply tax after discount
  2. Create a function to calculate compound interest
  3. Build a BMI (Body Mass Index) calculator
  4. Create a temperature converter (Celsius ↔ Fahrenheit)

📋 Math Object Quick Reference

Constants:
  • Math.PI - 3.141592653589793
  • Math.E - Euler's number (2.718)
  • Math.SQRT2 - √2 (1.414)
  • Math.LN2 - Natural log of 2
Min/Max:
  • Math.min(a, b, c...) - Smallest value
  • Math.max(a, b, c...) - Largest value
  • Math.abs(x) - Absolute value
  • Math.sign(x) - Sign (-1, 0, or 1)
Other Useful:
  • Math.log(x) - Natural logarithm
  • Math.exp(x) - e^x
  • Math.hypot(x, y) - √(x² + y²)
  • Math.random() - Random 0-1