Learn JavaScript for Web Development

JavaScript is most versatile languages to code applications for the browser, desktop, phone or tablet. Write program for client browser or web server. Build interactive web site with JavaScript.

JavaScript - Math Object


The JavaScript math object provides several constants and methods to perform mathematical operation. Unlike date object, it doesn't have constructors.

Math.sqrt(n)

The JavaScript math.sqrt(n) method returns the square root of the given number.

See this example:

Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>

Output:

Square Root of 17 is:

Math.random()

The JavaScript math.random() method returns the random number between 0 to 1.

See this example:

Random Number is: <span id="p2"></span>
<script>
document.getElementById('p2').innerHTML=Math.random();
</script>

Output:

Random Number is:

Math.pow(m,n)

The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.

See this example:

3 to the power of 4 is: <span id="p3"></span>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>

Output:

3 to the power of 4 is:

Math.floor(n)

The JavaScript math.floor(n) method returns the lowest integer for the given number. For example 3 for 3.7, 5 for 5.9 etc.

See this example:

Floor of 4.6 is: <span id="p4"></span>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>

Output:

Floor of 4.6 is:

Math.ceil(n)

The JavaScript math.ceil(n) method returns the largest integer for the given number. For example 4 for 3.7, 6 for 5.9 etc.

See this example:

Ceil of 4.6 is: <span id="p5"></span>
<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script>

Output:

Ceil of 4.6 is:

Math.round(n)

The JavaScript math.round(n) method returns the rounded integer nearest for the given number. If fractional part is equal or greater than 0.5, it goes to upper value 1 otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.

See this example:

Round of 4.3 is: <span id="p6"></span><br>
Round of 4.7 is: <span id="p7"></span>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>

Output:

Round of 4.3 is:
Round of 4.7 is:

Math.abs(n)

The JavaScript math.abs(n) method returns the absolute value for the given number. For example 4 for -4, 6.6 for -6.6 etc.

See this example:

Absolute value of -4 is: <span id="p8"></span>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script>

Output:

Absolute value of -4 is: