Mathematical Functions in JavaScript with example


In this JavaScript tutorial, we are going to learn "Math Object in JavaScript", and much more about Math Object in JavaScript with Examples

What is Math object in JavaScript?

  • The Math object in javascript is used to perform mathematical properties in our program.

  • Math object in JavaScript is static and it has no constructor.

  • It is used to perform mathematical operations in JavaScript such as logarithms, random number generation, and trigonometry.


Math object methods in JavaScript

1. Math.abs()

This JavaScript math object method returns the absolute value of a number

let num = -10;
let absoluteValue = Math.abs(num);

console.log(absoluteValue);

// Output: 10


2. Math.round()

This method is used to round a number to the nearest integer.

let num = 3.7;
let roundedNum = Math.round(num);

console.log(roundedNum);

// Output: 4


3. Math.floor()

This method rounds a number down to the nearest integer.

let num = 4.9;
let floorNum = Math.floor(num);

console.log(floorNum);

// Output: 4


4. Math.ceil()

The Math.ceil() method rounds a number up to the nearest integer.

let num = 2.1;
let ceilNum = Math.ceil(num);

console.log(ceilNum);

// Output: 3


5. Math.pow()

This method raises a number to a specified power.

let baseValue = 2;
let exponentValue = 3;
let result = Math.pow(baseValue, exponentValue);

console.log(result);

// Output: 8 (2^3 = 8)

6. Math.sqrt()

This JavaScript Math object method returns the square root of a number.

let num = 16;
let squareRoot = Math.sqrt(num);

console.log(squareRoot);

// Output: 4


7. Math.random()

This method is used to generate a random number between 0 (inclusive) and 1 (exclusive).

let randomNumber = Math.random();

console.log(randomNumber);

// Output: Random number will be between 0 and 1


8. Math.cbrt()

This method returns the cube root of the given number.

let cbrt = 8;
let result = Math.cbrt(cbrt);

console.log(result);

// Output: 2


9. Math.max()

It returns the maximum value of the given numbers.

let maximumValue = Math.max(23, 42, 54, 5, 2, 0, 23, 100);

console.log(maximumValue);

// Output: 100


10. Math.min()

It returns the minimum value of the given numbers.

let minimumValue = Math.min(23, 42, 54, 5, 2, 0, 23, 100);

console.log(minimumValue);

// Output: 0


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad