Javascript
JS Maths
what is the use of Math Object IN Js

The Math object in JavaScript offers methods and properties for mathematical calculations. It is a built-in object, so you can use it directly without creating an instance.

What is the Math Object?

The Math object is a built-in JavaScript object with properties and methods for mathematical operations. It has no constructor and works only with the Number type. All its properties and methods are static and can be accessed directly using Math.

For example, the cosine function is accessed using Math.cos(y), and the constant pi is accessed using Math.PI.

This article explores various methods and properties in JavaScript, starting with the Math properties and their uses.

Static Math Properties

The Math properties and their descriptions are listed below:

console.log("Math.PI :" + Math.PI);
console.log("Math.SQRT2:" + Math.SQRT2);
console.log("Math.SQRT1_2:" + Math.SQRT1_2);
console.log("Math.LN10:" + Math.LN10);
console.log("Math.LN2:" + Math.LN2);
console.log("Math.LOG10E:" + Math.LOG10E);
console.log("Math.LOG2E:" + Math.LOG2E);

Output:

Math.PI :3.141592653589793
Math.SQRT2:1.4142135623730951
Math.SQRT1_2:0.7071067811865476
Math.LN10:2.302585092994046
Math.LN2:0.6931471805599453
Math.LOG10E:0.4342944819032518
Math.LOG2E:1.44269504088...

Math Methods

The methods associated with the Math object are listed below, along with their descriptions.

console.log("ceil :" + Math.ceil(9.6));
console.log("floor :" + Math.floor(9.6));
console.log("round :" + Math.round(9.6));
console.log("sine :" + Math.sin(30));
console.log("cosine :" + Math.cos(30));
console.log("min :" + Math.min(30, 40));
console.log("max :" + Math.max(30, 40));
console.log("sign :" + Math.sign(-40));
console.log("abs :" + Math.abs(-40));

Output:

ceil :10
floor :9
round :10
sine :-0.9880316240928618
cosine :0.15425144988758405
min :30
max :40
sign :-1
abs :40

Common Use Cases of Math Object

The Math object is widely used in various scenarios such as:

  • Calculations: Performing arithmetic operations like addition, subtraction, multiplication, division, and more complex calculations involving trigonometric functions.
  • Random Number Generation: Generating random numbers for simulations, games, or random selections.
const randomNumber = Math.random();
console.log("Random number:", randomNumber);