JAVASCRIPT MATH

Lavanya



JavaScript Math


The JavaScript Math object offers various constants and methods for performing mathematical operations. Unlike the Date object, it does not have a constructor.

JavaScript Math Method 


Here is a list of JavaScript Math methods with their descriptions.


Math.sqrt(n)

The JavaScript `Math.sqrt(n)` method returns the square root of a given number.

Example 

<Script>

console.log(Math.sqrt(16));  

console.log(Math.sqrt(25));  

console.log(Math.sqrt(2));   

console.log(Math.sqrt(-1));

</Script>

Output:

4
5
1.4142135623730951
NaN

Math random()


The JavaScript `Math.random()` method returns a random number between 0 and 1.

Example 


<Script>

console.log(Math.random()); 

</Script>


Output: 

0.1234567890123456 (a random number between 0 and 1)

Math.pow(m,n)


The JavaScript `Math.pow(m, n)` method returns \(m\) raised to the power of \(n\), or \(m^n\).

Example 


<Script>

console.log(Math.pow(2, 3)); 

console.log(Math.pow(3, 4)); 

console.log(Math.pow(4, 2));

console.log(Math.pow(5, 1)); 

</Script>


Output :

8 (2 * 2 * 2)

81 (3 * 3 * 3 * 3)

16 (4 * 4)

5 (5 * 1)

Math.floor(n)


The JavaScript `Math.floor(n)` method returns the largest integer less than or equal to the given number. For example, it returns 3 for 3.7 and 5 for 5.9.

Example 

<Script>

console.log(Math.floor(3.7));

console.log(Math.floor(5.9)); 

console.log(Math.floor(7.1)); 

console.log(Math.floor(-3.7)); 

console.log(Math.floor(-5.9)); 

</Script>

Output:

3
5
7
-4
-6

Math.celi(n) 


The JavaScript `Math.ceil(n)` method returns the smallest integer greater than or equal to the given number. For example, it returns 4 for 3.7 and 6 for 5.9.

Example 


<Script>

console.log(Math.ceil(3.7)); 

console.log(Math.ceil(5.9)); 

console.log(Math.ceil(7.1)); 

console.log(Math.ceil(-3.7)); 

console.log(Math.ceil(-5.9)); 

</Script>

Output:

4
6
8
-3
-5

Math.round(n)


The JavaScript `Math.round(n)` method returns the integer nearest to the given number. If the fractional part is 0.5 or greater, it rounds up to the next integer; otherwise, it rounds down. For example, it returns 4 for 3.7, 3 for 3.3, and 6 for 5.9.

Example 


<Script>

console.log(Math.round(3.7)); 

console.log(Math.round(3.3)); 

console.log(Math.round(5.9)); 

console.log(Math.round(5.5)); 

console.log(Math.round(4.1)); 

</Script>

Output :

4
3
6
6
4

Math.abs(n)


The JavaScript `Math.abs(n)` method returns the absolute value of the given number. For example, it returns 4 for -4 and 6.6 for -6.6.

Example 


<Script>

console.log(Math.abs(-4)); 
console.log(Math.abs(-6.6)); 
console.log(Math.abs(3)); 
console.log(Math.abs(-0));

</Script>


Output :

4
6.6
3
0

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send