π The Math Object in JavaScript
π§ 1. Introduction to Math Object
The Math Object in JavaScript provides mathematical constants and functions for performing calculations.
π It is a built-in object and not a constructor, so it is used directly without creating an instance.
β Syntax:
Math.methodName(value);
π 2. Characteristics of Math Object
- Static object (no need to create object)
- Contains constants and methods
- Used for numeric calculations
- Does not work with complex numbers
π’ 3. Math Constants
| Constant | Description | Example |
|---|---|---|
Math.PI | Value of Ο | 3.14159 |
Math.E | Eulerβs number | 2.718 |
Math.SQRT2 | β2 | 1.414 |
Math.SQRT1_2 | β(1/2) | 0.707 |
π» Example:
console.log(Math.PI);
console.log(Math.E);
βοΈ 4. Important Math Methods
πΌ (1) Math.round()
Rounds to nearest integer
console.log(Math.round(4.6)); // 5
console.log(Math.round(4.3)); // 4
π½ (2) Math.floor()
Rounds down
console.log(Math.floor(4.9)); // 4
πΌ (3) Math.ceil()
Rounds up
console.log(Math.ceil(4.1)); // 5
βοΈ (4) Math.trunc()
Removes decimal part
console.log(Math.trunc(4.9)); // 4
π’ (5) Math.pow()
Power calculation
console.log(Math.pow(2, 3)); // 8
β (6) Math.sqrt()
Square root
console.log(Math.sqrt(16)); // 4
π² (7) Math.random()
Generates random number (0 to 1)
console.log(Math.random());
π― Random Number Example:
let num = Math.floor(Math.random() * 10);
console.log(num); // 0β9
π (8) Math.max()
Returns largest value
console.log(Math.max(10, 20, 30)); // 30
π½ (9) Math.min()
Returns smallest value
console.log(Math.min(10, 20, 30)); // 10
ββ (10) Math.abs()
Absolute value
console.log(Math.abs(-5)); // 5
π’ (11) Math.log()
Natural logarithm
console.log(Math.log(1)); // 0
π’ (12) Math.sin(), Math.cos(), Math.tan()
Trigonometric functions
console.log(Math.sin(0)); // 0
console.log(Math.cos(0)); // 1
π 5. Complete Example
let num = 5.7;
console.log("Round:", Math.round(num));
console.log("Floor:", Math.floor(num));
console.log("Ceil:", Math.ceil(num));
console.log("Power:", Math.pow(2, 3));
console.log("Square Root:", Math.sqrt(25));
console.log("Random:", Math.random());
console.log("Max:", Math.max(10, 50, 30));
console.log("Min:", Math.min(10, 50, 30));
π 6. Summary Table
| Method | Purpose |
|---|---|
| round() | Nearest integer |
| floor() | Round down |
| ceil() | Round up |
| trunc() | Remove decimal |
| pow() | Power |
| sqrt() | Square root |
| random() | Random number |
| max() | Largest value |
| min() | Smallest value |
| abs() | Absolute value |
β οΈ 7. Important Notes
- Math object is static
- No need to use
new Math() - Used widely in:
- Games (random numbers)
- Calculations
- Data analysis
π― Conclusion
The Math Object is essential for:
- Performing mathematical operations
- Generating random values
- Implementing logic-based applications
π It is widely used in web applications, games, and data processing.
