How to Use the Math.sign() Function in JavaScript?

Estimated read time 1 min read

The Math.sign() function in JavaScript is used to determine the sign of a number. It returns 1 if the number is positive, -1 if the number is negative, and 0 if the number is zero.

Here’s an example that uses the Math.sign() function:

console.log(Math.sign(7)); // Output: 1
console.log(Math.sign(-7)); // Output: -1
console.log(Math.sign(0)); // Output: 0

In the example above, the Math.sign() function is used to determine the sign of three different numbers. The first call to Math.sign(7) returns 1 because 7 is a positive number. The second call to Math.sign(-7) returns -1 because -7 is a negative number. The third call to Math.sign(0) returns 0 because 0 is neither positive nor negative.

The Math.sign() function can also be used with non-integer values, such as floating-point numbers:

console.log(Math.sign(3.14)); // Output: 1
console.log(Math.sign(-3.14)); // Output: -1

In the example above, the Math.sign() function is used to determine the sign of two floating-point numbers. The first call to Math.sign(3.14) returns 1 because 3.14 is a positive number. The second call to Math.sign(-3.14) returns -1 because -3.14 is a negative number.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply