JavaScript 25 🧬 Math Object
The Math object in JavaScript is a versatile tool for performing a wide range of mathematical operations. It provides everything you need to handle most mathematical tasks — from basic arithmetic and rounding to advanced functions like trigonometry and random number generation.
Note: Math is a built-in object — you don’t need to create it, and you can’t use it as a constructor. All methods and constants are accessed directly.
A Quick Look at the Examples
// Constants
console.log(Math.E); // 2.718281828459045
console.log(Math.PI); // 3.141592653589793
console.log(Math.SQRT2); // 1.4142135623730951
console.log(Math.LN2); // 0.6931471805599453
console.log(Math.LN10); // 2.302585092994046
// Rounding
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(4.9)); // 5
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(4.1)); // 4
// Exponential and logarithmic
console.log(Math.exp(1)); // 2.718281828459045
console.log(Math.pow(2, 3)); // 8
console.log(Math.log(Math.E)); // 1
// Basic
console.log(Math.abs(-5)); // 5
console.log(Math.sign(-5)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(5)); // 1
// Trigonometric
let angleInRadians = Math.PI / 2;
console.log(Math.sin(angleInRadians)); // 1
console.log(Math.asin(0.5)); // 0.5235987755982989 (~π/6)
// Misc
console.log(Math.max(1, 3, 2, 4)); // 4
console.log(Math.min(1, 3, 2, 4)); // 1
console.log(Math.random()); // e.g., 0.7345423...
a. Math Object Info and Constants
The Math object provides a collection of mathematical constants and methods. It’s a static object — you never call new Math().
Mathematical Constants
| Constant | Description | Value |
|---|---|---|
Math.E | Euler’s number (base of natural logarithm) | ≈ 2.718 |
Math.PI | Pi (ratio of circumference to diameter) | ≈ 3.14159 |
Math.SQRT2 | Square root of 2 | ≈ 1.414 |
Math.SQRT1_2 | Square root of 1/2 | ≈ 0.707 |
Math.LN2 | Natural logarithm of 2 | ≈ 0.693 |
Math.LN10 | Natural logarithm of 10 | ≈ 2.303 |
Math.LOG2E | Base-2 logarithm of E | ≈ 1.443 |
Math.LOG10E | Base-10 logarithm of E | ≈ 0.434 |
console.log(Math.E); // 2.718281828459045
console.log(Math.PI); // 3.141592653589793
console.log(Math.SQRT2); // 1.4142135623730951
console.log(Math.LN2); // 0.6931471805599453
console.log(Math.LN10); // 2.302585092994046
b. Math Object Methods — Part 1
Rounding Methods
| Method | Description | Example | Result |
|---|---|---|---|
Math.round(x) | Rounds to nearest integer | Math.round(4.5) | 5 |
Math.ceil(x) | Rounds up | Math.ceil(4.1) | 5 |
Math.floor(x) | Rounds down | Math.floor(4.9) | 4 |
Math.trunc(x) | Removes decimals | Math.trunc(4.9) | 4 |
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.round(-4.5)); // -4 (rounds toward +∞)
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(4.9)); // 5
console.log(Math.ceil(-4.1)); // -4
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(4.1)); // 4
console.log(Math.floor(-4.1)); // -5
Visual:
Number: -4.5 4.1 4.5 4.9
────────────────────────────
round: -4 4 5 5
ceil: -4 5 5 5
floor: -5 4 4 4
trunc: -4 4 4 4
Exponential and Logarithmic Functions
| Method | Description | Example | Result |
|---|---|---|---|
Math.exp(x) | E raised to power x | Math.exp(1) | 2.718... |
Math.pow(base, exp) | base ^ exp | Math.pow(2, 3) | 8 |
Math.log(x) | Natural log (base E) | Math.log(Math.E) | 1 |
Math.log2(x) | Base-2 log | Math.log2(8) | 3 |
Math.log10(x) | Base-10 log | Math.log10(1000) | 3 |
console.log(Math.exp(1)); // 2.718281828459045
console.log(Math.exp(2)); // 7.38905609893065
console.log(Math.pow(2, 3)); // 8
console.log(Math.pow(2, 10)); // 1024
console.log(Math.log(Math.E)); // 1
console.log(Math.log(1)); // 0
console.log(Math.log2(8)); // 3
console.log(Math.log10(1000)); // 3
Note: Math.pow(2, 3) can be written as 2 ** 3 (ES2016).
Other Basic Math Functions
| Method | Description | Example | Result |
|---|---|---|---|
Math.abs(x) | Absolute value | Math.abs(-5) | 5 |
Math.sign(x) | Sign (-1, 0, 1) | Math.sign(-5) | -1 |
Math.sqrt(x) | Square root | Math.sqrt(16) | 4 |
Math.cbrt(x) | Cube root | Math.cbrt(27) | 3 |
console.log(Math.abs(-5)); // 5
console.log(Math.abs(5)); // 5
console.log(Math.abs(-5.5)); // 5.5
console.log(Math.sign(-5)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(5)); // 1
console.log(Math.sign(-0)); // -0 (edge case!)
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(2)); // 1.4142135623730951
console.log(Math.cbrt(27)); // 3
c. Math Object Methods — Part 2
Trigonometric Functions
All trigonometric functions in JavaScript work in radians — not degrees.
| Method | Description | Example | Result |
|---|---|---|---|
Math.sin(x) | Sine | Math.sin(Math.PI / 2) | 1 |
Math.cos(x) | Cosine | Math.cos(0) | 1 |
Math.tan(x) | Tangent | Math.tan(Math.PI / 4) | 1 |
Math.asin(x) | Arcsine | Math.asin(0.5) | π/6 |
Math.acos(x) | Arccosine | Math.acos(1) | 0 |
Math.atan(x) | Arctangent | Math.atan(1) | π/4 |
Math.atan2(y, x) | Arctangent of y/x | Math.atan2(1, 1) | π/4 |
let angleInRadians = Math.PI / 2;
console.log(Math.sin(angleInRadians)); // 1
console.log(Math.cos(0)); // 1
console.log(Math.tan(Math.PI / 4)); // 1
console.log(Math.asin(0.5)); // 0.5235987755982989 (π/6)
console.log(Math.acos(1)); // 0
console.log(Math.atan(1)); // 0.7853981633974483 (π/4)
Degrees ↔ Radians conversion:
// Degrees to radians
const toRadians = (degrees) => degrees * (Math.PI / 180);
// Radians to degrees
const toDegrees = (radians) => radians * (180 / Math.PI);
console.log(Math.sin(toRadians(90))); // 1
console.log(Math.cos(toRadians(60))); // 0.5
console.log(toDegrees(Math.PI)); // 180
Miscellaneous Methods
| Method | Description | Example | Result |
|---|---|---|---|
Math.max(...nums) | Largest number | Math.max(1, 3, 2, 4) | 4 |
Math.min(...nums) | Smallest number | Math.min(1, 3, 2, 4) | 1 |
Math.random() | Random 0 ≤ x < 1 | Math.random() | e.g., 0.734... |
Math.hypot(...nums) | Square root of sum of squares | Math.hypot(3, 4) | 5 |
// Max and Min
console.log(Math.max(1, 3, 2, 4)); // 4
console.log(Math.min(1, 3, 2, 4)); // 1
console.log(Math.max()); // -Infinity (no args!)
console.log(Math.min()); // Infinity (no args!)
// With arrays — use spread
const nums = [3, 1, 4, 1, 5, 9, 2, 6];
console.log(Math.max(...nums)); // 9
console.log(Math.min(...nums)); // 1
// Random
console.log(Math.random()); // e.g., 0.7345423...
// Hypotenuse (Pythagorean theorem)
console.log(Math.hypot(3, 4)); // 5
console.log(Math.hypot(5, 12)); // 13
Random Number Formulas
| Goal | Formula | Example |
|---|---|---|
| 0 ≤ x < 1 | Math.random() | 0.734... |
| 0 ≤ x < n | Math.random() * n | 0 ≤ x < 10 |
| Integer 0 to n-1 | Math.floor(Math.random() * n) | 0, 1, ..., n-1 |
| Integer 1 to n | Math.floor(Math.random() * n) + 1 | 1, 2, ..., n |
| Integer min to max | Math.floor(Math.random() * (max - min + 1)) + min | Range inclusive |
// Random 0 to 9
console.log(Math.floor(Math.random() * 10));
// Random 1 to 6 (dice roll)
console.log(Math.floor(Math.random() * 6) + 1);
// Random 10 to 20 (inclusive)
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomBetween(10, 20));
// Random element from array
const items = ['apple', 'banana', 'cherry'];
const randomItem = items[Math.floor(Math.random() * items.length)];
console.log(randomItem);
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Math Object</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
color: #333;
line-height: 1.6;
}
h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
.demo-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin: 15px 0;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.8;
}
.keyword { color: #569cd6; }
.string { color: #ce9178; }
.number { color: #b5cea8; }
.function { color: #dcdcaa; }
.comment { color: #6a9955; }
.boolean { color: #569cd6; }
#output {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
min-height: 40px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
table {
width: 100%;
border-collapse: collapse;
margin: 15px 0;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th { background: #007bff; color: white; }
tr:nth-child(even) { background: #f8f9fa; }
.btn {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 6px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
margin: 5px;
transition: all 0.3s;
}
.btn:hover {
background: #0056b3;
transform: translateY(-2px);
}
.btn-success { background: #28a745; }
.btn-success:hover { background: #1e7e34; }
.btn-warning { background: #ffc107; color: #333; }
.btn-warning:hover { background: #d39e00; }
.result-display {
font-family: 'Courier New', monospace;
font-size: 2em;
color: #007bff;
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin: 15px 0;
border-left: 4px solid #007bff;
text-align: center;
font-weight: bold;
}
.input-group {
margin: 10px 0;
}
.input-group label {
display: inline-block;
min-width: 150px;
font-weight: bold;
}
.input-group input {
padding: 8px 12px;
border: 2px solid #ddd;
border-radius: 6px;
font-size: 1em;
width: 150px;
}
.input-group input:focus {
outline: none;
border-color: #007bff;
}
</style>
</head>
<body>
<h1>The Math Object</h1>
<div class="demo-box">
<h2>1. Math Constants</h2>
<pre>
console.log(Math.E); <span class="comment">// 2.718281828459045</span>
console.log(Math.PI); <span class="comment">// 3.141592653589793</span>
console.log(Math.SQRT2); <span class="comment">// 1.4142135623730951</span>
console.log(Math.LN2); <span class="comment">// 0.6931471805599453</span>
console.log(Math.LN10); <span class="comment">// 2.302585092994046</span>
</pre>
</div>
<div class="demo-box">
<h2>2. Rounding Methods</h2>
<pre>
console.log(Math.round(<span class="number">4.5</span>)); <span class="comment">// 5</span>
console.log(Math.round(<span class="number">4.4</span>)); <span class="comment">// 4</span>
console.log(Math.ceil(<span class="number">4.1</span>)); <span class="comment">// 5</span>
console.log(Math.ceil(<span class="number">4.9</span>)); <span class="comment">// 5</span>
console.log(Math.floor(<span class="number">4.9</span>)); <span class="comment">// 4</span>
console.log(Math.floor(<span class="number">4.1</span>)); <span class="comment">// 4</span>
</pre>
</div>
<div class="demo-box">
<h2>3. Rounding Comparison</h2>
<table>
<tr>
<th>Number</th>
<th>round()</th>
<th>ceil()</th>
<th>floor()</th>
<th>trunc()</th>
</tr>
<tr><td>4.1</td><td>4</td><td>5</td><td>4</td><td>4</td></tr>
<tr><td>4.5</td><td>5</td><td>5</td><td>4</td><td>4</td></tr>
<tr><td>4.9</td><td>5</td><td>5</td><td>4</td><td>4</td></tr>
<tr><td>-4.1</td><td>-4</td><td>-4</td><td>-5</td><td>-4</td></tr>
<tr><td>-4.5</td><td>-4</td><td>-4</td><td>-5</td><td>-4</td></tr>
<tr><td>-4.9</td><td>-5</td><td>-4</td><td>-5</td><td>-4</td></tr>
</table>
</div>
<div class="demo-box">
<h2>4. Exponential & Logarithmic</h2>
<pre>
console.log(Math.exp(<span class="number">1</span>)); <span class="comment">// 2.718281828459045</span>
console.log(Math.pow(<span class="number">2</span>, <span class="number">3</span>)); <span class="comment">// 8</span>
console.log(Math.log(Math.E)); <span class="comment">// 1</span>
console.log(Math.log2(<span class="number">8</span>)); <span class="comment">// 3</span>
console.log(Math.log10(<span class="number">1000</span>)); <span class="comment">// 3</span>
</pre>
</div>
<div class="demo-box">
<h2>5. Basic Math Functions</h2>
<pre>
console.log(Math.abs(-<span class="number">5</span>)); <span class="comment">// 5</span>
console.log(Math.sign(-<span class="number">5</span>)); <span class="comment">// -1</span>
console.log(Math.sign(<span class="number">0</span>)); <span class="comment">// 0</span>
console.log(Math.sign(<span class="number">5</span>)); <span class="comment">// 1</span>
console.log(Math.sqrt(<span class="number">16</span>)); <span class="comment">// 4</span>
console.log(Math.cbrt(<span class="number">27</span>)); <span class="comment">// 3</span>
</pre>
</div>
<div class="demo-box">
<h2>6. Trigonometric Functions</h2>
<pre>
<span class="keyword">let</span> angleInRadians = Math.PI / <span class="number">2</span>;
console.log(Math.sin(angleInRadians)); <span class="comment">// 1</span>
console.log(Math.asin(<span class="number">0.5</span>)); <span class="comment">// π/6 (0.523...)</span>
<span class="comment">// Degrees to radians conversion</span>
<span class="keyword">const</span> toRadians = (deg) => deg * (Math.PI / <span class="number">180</span>);
console.log(Math.sin(toRadians(<span class="number">90</span>))); <span class="comment">// 1</span>
</pre>
</div>
<div class="demo-box">
<h2>7. Max, Min & Random</h2>
<pre>
console.log(Math.max(<span class="number">1</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">4</span>)); <span class="comment">// 4</span>
console.log(Math.min(<span class="number">1</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">4</span>)); <span class="comment">// 1</span>
console.log(Math.random()); <span class="comment">// e.g., 0.734...</span>
<span class="comment">// Random integer 1 to 6 (dice)</span>
console.log(Math.floor(Math.random() * <span class="number">6</span>) + <span class="number">1</span>);
</pre>
</div>
<div class="demo-box">
<h2>8. Interactive: Math Playground</h2>
<div class="input-group">
<label for="mathInput">Enter a number:</label>
<input type="number" id="mathInput" value="4.7" step="0.1">
</div>
<div style="margin: 10px 0;">
<button class="btn" onclick="runOp('round')">round()</button>
<button class="btn" onclick="runOp('ceil')">ceil()</button>
<button class="btn" onclick="runOp('floor')">floor()</button>
<button class="btn" onclick="runOp('trunc')">trunc()</button>
<button class="btn" onclick="runOp('abs')">abs()</button>
<button class="btn" onclick="runOp('sign')">sign()</button>
<button class="btn" onclick="runOp('sqrt')">sqrt()</button>
<button class="btn" onclick="runOp('pow')">pow(2)</button>
<button class="btn" onclick="runOp('log')">log()</button>
</div>
<div class="result-display" id="mathResult">Result will appear here</div>
<div id="mathDetails"></div>
</div>
<div class="demo-box">
<h2>9. Interactive: Random Generator</h2>
<div style="text-align: center;">
<button class="btn btn-success" onclick="rollDice()">🎲 Roll Dice (1-6)</button>
<button class="btn btn-warning" onclick="randomNumber()">🔢 Random 1-100</button>
<button class="btn" onclick="randomColor()">🎨 Random Color</button>
</div>
<div class="result-display" id="randomResult">Click a button!</div>
<div id="randomDetails"></div>
</div>
<div class="demo-box">
<h2>10. Live Output — All Examples</h2>
<div id="output">Loading...</div>
</div>
<script>
// ============================================
// Math Object — Live Demo
// ============================================
let results = [];
// 1. Constants
results.push('📌 Math Constants:\n');
results.push(' Math.E → ' + Math.E);
results.push(' Math.PI → ' + Math.PI);
results.push(' Math.SQRT2 → ' + Math.SQRT2);
results.push(' Math.LN2 → ' + Math.LN2);
results.push(' Math.LN10 → ' + Math.LN10);
results.push('');
// 2. Rounding
results.push('📌 Rounding Methods:\n');
results.push(' Math.round(4.5) → ' + Math.round(4.5));
results.push(' Math.round(4.4) → ' + Math.round(4.4));
results.push(' Math.ceil(4.1) → ' + Math.ceil(4.1));
results.push(' Math.ceil(4.9) → ' + Math.ceil(4.9));
results.push(' Math.floor(4.9) → ' + Math.floor(4.9));
results.push(' Math.floor(4.1) → ' + Math.floor(4.1));
results.push(' Math.trunc(4.9) → ' + Math.trunc(4.9));
results.push('');
// 3. Exponential and logarithmic
results.push('📌 Exponential & Logarithmic:\n');
results.push(' Math.exp(1) → ' + Math.exp(1));
results.push(' Math.pow(2, 3) → ' + Math.pow(2, 3));
results.push(' Math.pow(2, 10) → ' + Math.pow(2, 10));
results.push(' Math.log(Math.E) → ' + Math.log(Math.E));
results.push(' Math.log2(8) → ' + Math.log2(8));
results.push(' Math.log10(1000) → ' + Math.log10(1000));
results.push('');
// 4. Basic
results.push('📌 Basic Math Functions:\n');
results.push(' Math.abs(-5) → ' + Math.abs(-5));
results.push(' Math.sign(-5) → ' + Math.sign(-5));
results.push(' Math.sign(0) → ' + Math.sign(0));
results.push(' Math.sign(5) → ' + Math.sign(5));
results.push(' Math.sqrt(16) → ' + Math.sqrt(16));
results.push(' Math.cbrt(27) → ' + Math.cbrt(27));
results.push('');
// 5. Trigonometric
results.push('📌 Trigonometric Functions:\n');
const angleInRadians = Math.PI / 2;
results.push(' Math.sin(Math.PI / 2) → ' + Math.sin(angleInRadians));
results.push(' Math.cos(0) → ' + Math.cos(0));
results.push(' Math.tan(Math.PI / 4) → ' + Math.tan(Math.PI / 4));
results.push(' Math.asin(0.5) → ' + Math.asin(0.5));
results.push('');
// 6. Max, min, random
results.push('📌 Max, Min, Random:\n');
results.push(' Math.max(1, 3, 2, 4) → ' + Math.max(1, 3, 2, 4));
results.push(' Math.min(1, 3, 2, 4) → ' + Math.min(1, 3, 2, 4));
const nums = [3, 1, 4, 1, 5, 9, 2, 6];
results.push(' Math.max(...[' + nums.join(', ') + ']) → ' + Math.max(...nums));
results.push(' Math.min(...[' + nums.join(', ') + ']) → ' + Math.min(...nums));
results.push('');
// 7. Random formulas
results.push('📌 Random Number Formulas:\n');
results.push(' Random 0-9: Math.floor(Math.random() * 10)');
results.push(' Dice roll 1-6: Math.floor(Math.random() * 6) + 1');
results.push(' Range 10-20: Math.floor(Math.random() * 11) + 10');
results.push('');
// 8. Hypot
results.push('📌 Hypotenuse (Pythagorean):\n');
results.push(' Math.hypot(3, 4) → ' + Math.hypot(3, 4));
results.push(' Math.hypot(5, 12) → ' + Math.hypot(5, 12));
results.push('');
// 9. Practical: Distance between two points
results.push('📌 Practical: Distance Between Points:\n');
function distance(x1, y1, x2, y2) {
return Math.hypot(x2 - x1, y2 - y1);
}
results.push(' distance(0, 0, 3, 4) → ' + distance(0, 0, 3, 4));
results.push(' distance(1, 1, 4, 5) → ' + distance(1, 1, 4, 5).toFixed(2));
results.push('');
// 10. Practical: Circle
results.push('📌 Practical: Circle Calculations:\n');
function circleArea(radius) {
return Math.PI * radius ** 2;
}
function circleCircumference(radius) {
return 2 * Math.PI * radius;
}
results.push(' circleArea(5) → ' + circleArea(5).toFixed(2));
results.push(' circleCircumference(5) → ' + circleCircumference(5).toFixed(2));
results.push('');
// 11. Practical: Clamp
results.push('📌 Practical: Clamp Value:\n');
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
results.push(' clamp(15, 0, 10) → ' + clamp(15, 0, 10));
results.push(' clamp(-5, 0, 10) → ' + clamp(-5, 0, 10));
results.push(' clamp(5, 0, 10) → ' + clamp(5, 0, 10));
document.getElementById('output').textContent = results.join('\n');
// ============================================
// Interactive: Math Playground
// ============================================
const mathOps = {
round: { fn: (n) => Math.round(n), name: 'Math.round' },
ceil: { fn: (n) => Math.ceil(n), name: 'Math.ceil' },
floor: { fn: (n) => Math.floor(n), name: 'Math.floor' },
trunc: { fn: (n) => Math.trunc(n), name: 'Math.trunc' },
abs: { fn: (n) => Math.abs(n), name: 'Math.abs' },
sign: { fn: (n) => Math.sign(n), name: 'Math.sign' },
sqrt: { fn: (n) => Math.sqrt(n), name: 'Math.sqrt' },
pow: { fn: (n) => Math.pow(n, 2), name: 'Math.pow' },
log: { fn: (n) => Math.log(n), name: 'Math.log' }
};
function runOp(op) {
const num = Number(document.getElementById('mathInput').value);
const result = mathOps[op].fn(num);
const resultStr = Number.isInteger(result) ? result : result.toFixed(6);
document.getElementById('mathResult').textContent = resultStr;
document.getElementById('mathDetails').innerHTML =
`<p><code>${mathOps[op].name}(${num}) → ${resultStr}</code></p>`;
}
// ============================================
// Interactive: Random Generator
// ============================================
function rollDice() {
const roll = Math.floor(Math.random() * 6) + 1;
const emoji = ['⚀', '⚁', '⚂', '⚃', '⚄', '⚅'][roll - 1];
document.getElementById('randomResult').textContent = `${emoji} ${roll}`;
document.getElementById('randomDetails').innerHTML =
`<p><code>Math.floor(Math.random() * 6) + 1 → ${roll}</code></p>`;
}
function randomNumber() {
const num = Math.floor(Math.random() * 100) + 1;
document.getElementById('randomResult').textContent = num;
document.getElementById('randomDetails').innerHTML =
`<p><code>Math.floor(Math.random() * 100) + 1 → ${num}</code></p>`;
}
function randomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const color = `rgb(${r}, ${g}, ${b})`;
const hex = '#' + [r, g, b].map(c => c.toString(16).padStart(2, '0')).join('');
const display = document.getElementById('randomResult');
display.textContent = hex;
display.style.color = color;
document.getElementById('randomDetails').innerHTML =
`<p><code>rgb(${r}, ${g}, ${b})</code></p>`;
}
</script>
</body>
</html>
Quick Reference
Constants
| Constant | Value | Description |
|---|---|---|
Math.E | 2.718 | Euler’s number |
Math.PI | 3.14159 | Pi |
Math.SQRT2 | 1.414 | √2 |
Math.LN2 | 0.693 | ln(2) |
Math.LN10 | 2.303 | ln(10) |
Rounding
| Method | Description | Example | Result |
|---|---|---|---|
round() | Nearest integer | Math.round(4.5) | 5 |
ceil() | Round up | Math.ceil(4.1) | 5 |
floor() | Round down | Math.floor(4.9) | 4 |
trunc() | Remove decimals | Math.trunc(4.9) | 4 |
Exponential & Logarithmic
| Method | Description | Example | Result |
|---|---|---|---|
exp(x) | E^x | Math.exp(1) | 2.718 |
pow(b, e) | b^e | Math.pow(2, 3) | 8 |
log(x) | ln(x) | Math.log(Math.E) | 1 |
log2(x) | log₂(x) | Math.log2(8) | 3 |
log10(x) | log₁₀(x) | Math.log10(1000) | 3 |
Basic
| Method | Description | Example | Result |
|---|---|---|---|
abs(x) | Absolute value | Math.abs(-5) | 5 |
sign(x) | Sign (-1, 0, 1) | Math.sign(-5) | -1 |
sqrt(x) | Square root | Math.sqrt(16) | 4 |
cbrt(x) | Cube root | Math.cbrt(27) | 3 |
Trigonometric (radians)
| Method | Description | Example | Result |
|---|---|---|---|
sin(x) | Sine | Math.sin(Math.PI/2) | 1 |
cos(x) | Cosine | Math.cos(0) | 1 |
tan(x) | Tangent | Math.tan(Math.PI/4) | 1 |
asin(x) | Arcsine | Math.asin(0.5) | π/6 |
acos(x) | Arccosine | Math.acos(1) | 0 |
atan(x) | Arctangent | Math.atan(1) | π/4 |
Miscellaneous
| Method | Description | Example | Result |
|---|---|---|---|
max(...) | Largest | Math.max(1, 3, 2, 4) | 4 |
min(...) | Smallest | Math.min(1, 3, 2, 4) | 1 |
random() | Random 0 ≤ x < 1 | Math.random() | 0.734... |
hypot(...) | √(x² + y²) | Math.hypot(3, 4) | 5 |
Random Number Formulas
| Goal | Formula |
|---|---|
| 0 ≤ x < 1 | Math.random() |
| Integer 0 to n-1 | Math.floor(Math.random() * n) |
| Integer 1 to n | Math.floor(Math.random() * n) + 1 |
| Integer min to max (inclusive) | Math.floor(Math.random() * (max - min + 1)) + min |
| Random array element | arr[Math.floor(Math.random() * arr.length)] |
Best Practices
✅ Do This:
// Use spread for arrays with max/min
const nums = [3, 1, 4, 1, 5];
Math.max(...nums); // 5
// Use Math.hypot for distances
function distance(x1, y1, x2, y2) {
return Math.hypot(x2 - x1, y2 - y1);
}
// Create a random integer helper
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Use Math.PI for circle calculations
const area = Math.PI * radius ** 2;
// Convert degrees to radians for trig functions
const toRadians = deg => deg * (Math.PI / 180);
Math.sin(toRadians(90)); // 1
// Clamp values
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
❌ Don’t Do This:
// Don't forget to spread arrays
const nums = [1, 2, 3];
Math.max(nums); // ❌ NaN
Math.max(...nums); // ✅ 3
// Don't use degrees with trig functions
Math.sin(90); // ❌ Not 1 (90 radians!)
Math.sin(90 * Math.PI / 180); // ✅ 1
// Don't use Math.random() for crypto
Math.random(); // ⚠️ Not cryptographically secure
// Use crypto.getRandomValues() for security
// Don't forget floor + max for ranges
Math.random() * 6; // ❌ 0 to 5.999...
Math.floor(Math.random() * 6) + 1; // ✅ 1 to 6
// Don't use Math.pow when ** works
Math.pow(2, 3); // Works, but 2 ** 3 is shorter
Common Pitfalls
| Pitfall | Problem | Solution |
|---|---|---|
Math.max([1, 2, 3]) | NaN (array not spread) | Math.max(...[1, 2, 3]) |
Math.sin(90) | Uses radians, not degrees | Convert: 90 * Math.PI / 180 |
Math.random() for security | Not cryptographically secure | Use crypto.getRandomValues() |
Math.round(-4.5) | Returns -4, not -5 | Round half toward +∞ |
Math.max() with no args | Returns -Infinity | Always pass arguments |
Math.sqrt(-1) | Returns NaN | Check for negatives first |
Pro Tip: The Math object is your go-to for mathematical operations. Remember: trigonometric functions work in radians — convert degrees with deg * Math.PI / 180. Use spread with max/min for arrays: Math.max(...arr). Create random integers with Math.floor(Math.random() * (max - min + 1)) + min. Use Math.hypot() for distances and the Pythagorean theorem. And for cryptographic security, don’t use Math.random() — use crypto.getRandomValues() instead!
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!