Skip to main content

JavaScript Numbers & Math

JavaScript Math Object

Written by Published

Math is a built-in object holding mathematical constants and functions.

You never create a Math object; everything on it is static.

Call the methods directly on Math.

Example

Example

javascript

console.log(Math.abs(-5));
console.log(Math.sqrt(16));
console.log(Math.PI);

The output is 5, 4, then pi.

What Math Provides

Constants such as Math.PI and Math.E.

Functions such as abs, sqrt, pow and sign.

Rounding and random, which have their own lessons.

Syntax

Syntax

javascript

Math.abs(value);
Math.sqrt(value);

Math is never used with new.

Absolute Value

abs removes the sign, which is useful for differences.

Example

Example

javascript

console.log(Math.abs(-5));
console.log(Math.abs(5));
console.log(Math.abs(3 - 8));

The last one is the distance between two numbers.

Powers and Roots

pow and the ** operator do the same job.

Example

Example

javascript

console.log(Math.pow(2, 10));
console.log(2 ** 10);
console.log(Math.sqrt(144));
console.log(Math.cbrt(27));

** is the modern way to write a power.

The Sign of a Number

sign returns -1, 0 or 1.

Example

Example

javascript

console.log(Math.sign(-42));
console.log(Math.sign(0));
console.log(Math.sign(42));

Useful for deciding a direction.

Constants

Math.PI is the one you will actually use.

Example

Example

javascript

const radius = 3;

console.log(Math.PI > 3.14 && Math.PI < 3.15);
console.log(Math.round(Math.PI * radius * radius));

The area of the circle, rounded, is 28.

Everything Is Static

Trying to create a Math object throws an error.

Example

Example

javascript

let message;

try {
  new Math();
} catch (error) {
  message = "Math is not a constructor";
}

console.log(message);

It is a collection of tools, not a type of thing.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Math Object</title>
</head>
<body>

  <h1>The Math Object</h1>

  <p id="out"></p>

  <script>
    const radius = 5;

    document.getElementById("out").innerHTML =
      "Circle area: " + (Math.PI * radius * radius).toFixed(2) +
      "<br>Square root of 144: " + Math.sqrt(144) +
      "<br>2 to the power 10: " + Math.pow(2, 10) +
      "<br>Distance between 3 and 8: " + Math.abs(3 - 8);
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try a bigger circle:

Change the radius and watch the area change.

Important Points

  • Math is a built-in object of static tools.
  • Math.abs removes the sign.
  • Math.sqrt and Math.pow handle roots and powers.
  • Math.PI is the circle constant.
  • Math is never used with new.

Conclusion

Math collects the calculations that are not operators.

You will meet abs, sqrt and PI most often.

Rounding and random are common enough to deserve their own lessons.