js Math

The Math object in JavaScript provides a collection of constants and methods to perform mathematical operations. Unlike many other objects in JavaScript, the Math object is not a constructor and is not instantiated; instead, it is a static object with properties and methods that are accessed directly.

Key Properties and Methods of the Math Object

Here’s a brief overview of some of the most commonly used properties and methods of the Math object:

Method/Property Description Example Output
Math.PI Value of π (pi) Math.PI
Math.E Value of Euler’s number Math.E
Math.SQRT2 Square root of 2 Math.SQRT2
Math.SQRT1_2 Square root of 1/2 Math.SQRT1_2
Math.LN2 Natural log of 2 Math.LN2
Math.LN10 Natural log of 10 Math.LN10
Math.LOG2E Log base 2 of e Math.LOG2E
Math.LOG10E Log base 10 of e Math.LOG10E
Math.abs(x) Absolute value of x Math.abs(-5)
Math.ceil(x) Smallest integer greater than or equal to x Math.ceil(4.3)
Math.floor(x) Largest integer less than or equal to x Math.floor(4.7)
Math.round(x) Round x to the nearest integer Math.round(4.5)
Math.max(x1, x2, ...) Largest of zero or more numbers Math.max(1, 5, 10)
Math.min(x1, x2, ...) Smallest of zero or more numbers Math.min(1, 5, 10)
Math.random() Random number between 0 (inclusive) and 1 (exclusive) Math.random()
Math.pow(base, exponent) Base raised to the power of exponent Math.pow(2, 3)
Math.sqrt(x) Square root of x Math.sqrt(16)

Here's an example HTML file demonstrating some of the Math object's properties and methods:

Example:

<script>
document.write("Value of PI: " + Math.PI );
document.write("Value of E: " + Math.E );
document.write("Square root of 2: " + Math.SQRT2 );
document.write("Square root of 1/2: " + Math.SQRT1_2 );
document.write("Natural log of 2: " + Math.LN2 );
document.write("Natural log of 10: " + Math.LN10 );
document.write("Log base 2 of E: " + Math.LOG2E );
document.write("Log base 10 of E: " + Math.LOG10E );
document.write("Absolute value of -5: " + Math.abs(-5) );
document.write("Ceiling of 4.3: " + Math.ceil(4.3) );
document.write("Floor of 4.7: " + Math.floor(4.7) );
document.write("Round 4.5: " + Math.round(4.5) );
document.write("Max of 1, 5, 10: " + Math.max(1, 5, 10) );
document.write("Min of 1, 5, 10: " + Math.min(1, 5, 10) );
document.write("Random number: " + Math.random() );
document.write("2 raised to the power 3: " + Math.pow(2, 3) );
document.write("Square root of 16: " + Math.sqrt(16) );
</script>

Output:

Value of PI: 3.141592653589793
Value of E: 2.718281828459045
Square root of 2: 1.4142135623730951
Square root of 1/2: 0.7071067811865476
Natural log of 2: 0.6931471805599453
Natural log of 10: 2.302585092994046
Log base 2 of E: 1.4426950408889634
Log base 10 of E: 0.4342944819032518
Absolute value of -5: 5
Ceiling of 4.3: 5
Floor of 4.7: 4
Round 4.5: 5
Max of 1, 5, 10: 10
Min of 1, 5, 10: 1
Random number: 0.842160965484509
2 raised to the power 3: 8
Square root of 16: 4