How to Use the Math Object in JavaScript?

Estimated read time 2 min read

The Math object in JavaScript is a built-in object that provides a set of mathematical functions and constants. Here are some common methods and properties of the Math object:

  • Math.abs(x) returns the absolute value of x.
  • Math.ceil(x) returns the smallest integer greater than or equal to x.
  • Math.floor(x) returns the largest integer less than or equal to x.
  • Math.round(x) returns the value of x rounded to the nearest integer.
  • Math.max(a, b, c, ...) returns the largest of zero or more numbers.
  • Math.min(a, b, c, ...) returns the smallest of zero or more numbers.
  • Math.pow(x, y) returns the value of x raised to the power of y.
  • Math.sqrt(x) returns the square root of x.
  • Math.E is the mathematical constant e (approx. 2.718).
  • Math.PI is the mathematical constant pi (approx. 3.14).
  • Math.random() returns a random number between 0 and 1.

Here’s an example of how to use the Math object to perform some common mathematical operations:

let x = -5;
let y = 2;

let absoluteValue = Math.abs(x);
let ceiling = Math.ceil(y);
let floor = Math.floor(y);
let rounded = Math.round(y);
let maximum = Math.max(x, y);
let minimum = Math.min(x, y);
let power = Math.pow(x, y);
let squareRoot = Math.sqrt(y);

console.log(`Absolute value of ${x}: ${absoluteValue}`);
console.log(`Ceiling of ${y}: ${ceiling}`);
console.log(`Floor of ${y}: ${floor}`);
console.log(`Rounded value of ${y}: ${rounded}`);
console.log(`Maximum of ${x} and ${y}: ${maximum}`);
console.log(`Minimum of ${x} and ${y}: ${minimum}`);
console.log(`${x} raised to the power of ${y}: ${power}`);
console.log(`Square root of ${y}: ${squareRoot}`);

This will output the following:

Absolute value of -5: 5
Ceiling of 2: 2
Floor of 2: 2
Rounded value of 2: 2
Maximum of -5 and 2: 2
Minimum of -5 and 2: -5
-5 raised to the power of 2: 25
Square root of 2: 1.4142135623730951

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply