Loading

Math in JavaScript

  • JavaScript provides a set of built-in mathematical operations and functions that allow you to perform various mathematical calculations.

Math methods in JavaScript:

Math.sqrt(x):

  • Returns the square root of a number x.

Syntax:

const squareRoot = Math.sqrt(16); // Returns 4

Example:

<!DOCTYPE html>
<html>

<body>

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

</body>

</html>

Output:

Square Root of 17 is: 4.123105625617661


Math.pow(x, y): 

  • Returns x raised to the power of y.

Syntax:

const result = Math.pow(2, 3); // Returns 8 (2^3)

Example:

<!DOCTYPE html>
<html>

<body>

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

</body>

</html>

Output:

3 to the power of 4 is: 81


Math.floor(x):

  •  Rounds a number x down to the nearest integer.
const floored = Math.floor(3.9); // Returns 3

Example:

<!DOCTYPE html>
<html>

<body>

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

</body>

</html>

Output:

Floor of 4.6 is: 4