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.
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-decrementx--- 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.
Common Methods:
Math.round()- Round to nearest integerMath.ceil()- Round upMath.floor()- Round downMath.trunc()- Remove decimal part
Power & Roots:
Math.pow(x, y)- x to the power yMath.sqrt(x)- Square rootMath.cbrt(x)- Cube root
Trigonometry:
Math.sin(x)- Sine (radians)Math.cos(x)- CosineMath.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.
💡 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.
📝 Try These Challenges:
- Modify the discount calculator to apply tax after discount
- Create a function to calculate compound interest
- Build a BMI (Body Mass Index) calculator
- Create a temperature converter (Celsius ↔ Fahrenheit)
📋 Math Object Quick Reference
Constants:
Math.PI- 3.141592653589793Math.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 valueMath.max(a, b, c...)- Largest valueMath.abs(x)- Absolute valueMath.sign(x)- Sign (-1, 0, or 1)
Other Useful:
Math.log(x)- Natural logarithmMath.exp(x)- e^xMath.hypot(x, y)- √(x² + y²)Math.random()- Random 0-1