JavaScript Math
The Math object in JavaScript provides constants and methods for mathematical operations, including rounding, trigonometry, exponentiation, and more. It's a powerful tool for performing calculations and manipulating numeric values.
Key Topics
Math Constants
Constants like Math.PI and Math.E represent mathematical constants for use in calculations.
console.log(Math.PI);
console.log(Math.E);
Output
> 3.141592653589793
> 2.718281828459045
Explanation: Math.PI and Math.E give the values of π and Euler's number, useful in various calculations.
Common Math Methods
Methods like Math.round(), Math.sqrt(), and Math.abs() simplify numeric operations.
console.log(Math.round(3.6));
console.log(Math.sqrt(16));
console.log(Math.abs(-5));
Output
> 4
> 4
> 5
Explanation: Math.round(3.6) rounds to 4, Math.sqrt(16) returns 4, and Math.abs(-5) returns 5.
JavaScript Usage in DOM
This DOM-based example shows how math operations can calculate values and display them on the webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math in DOM</title>
</head>
<body>
<h1>Math Demo</h1>
<button onclick="calculate()">Calculate</button>
<p id="display"></p>
<script>
function calculate() {
let value = Math.round(Math.PI);
document.getElementById("display").textContent = "Rounded PI: " + value;
}
</script>
</body>
</html>
Key Takeaways
- Constants:
Math.PI,Math.Eprovide important values. - Methods:
round(),sqrt(),abs()and others simplify calculations. - DOM Integration: Perform math operations and display results dynamically.