The Wayback Machine - https://web.archive.org/web/20241217194820/https://www.geeksforgeeks.org/javascript-math-sign-method/
Open In App

Javascript Math sign() Method

Last Updated : 15 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Math.sign() is a built-in method in JavaScript and is used to know the sign of a number, indicating whether the number specified is negative or positive.

Syntax:

Math.sign(number)

Parameters:

  • This method accepts a single parameter number which represents the number whose sign you want to know. 

Return Value:

The Math.sign() method returns five different values as described below:

  • It returns 1 if the argument passed is a positive number.
  • It returns -1 if the argument passed is a negative number.
  • It returns 0 if the argument passed is a positive zero.
  • It returns -0 if the argument passed is a negative zero.
  • If none of the above cases match, it returns Nan.

Example 1: When a positive number is passed as an argument. 

JavaScript
console.log(Math.sign(2));  

Output
1

Example 2: When a negative number is passed as an argument: 

JavaScript
console.log(Math.sign(-2));  

Output
-1

Example 3: When a positive zero is passed as an argument: 

JavaScript
console.log(Math.sign(0)); 

Output
0

Example 4: When a negative zero is passed as an argument: 

JavaScript
console.log(Math.sign(-0));

Output
-0

Example 5: When an invalid number is passed as an argument: 

JavaScript
console.log(Math.sign(haa));  

Output:

NaN

We have a complete list of Javascript Math Objects methods, to check those please go through this Javascript Math Object Complete reference article.

Supported Browsers

  • Chrome 51
  • Edge 15
  • Firefox 54
  • Safari 10
  • Opera 38

Javascript Math sign() Method – FAQs

What does the Math.sign() method do in JavaScript?

The Math.sign() method returns the sign of a number, indicating whether the number is positive, negative, or zero.

What happens if the argument is not a number?

If the argument is not a number, Math.sign() first attempts to convert it to a number. If the conversion is not possible, the result is NaN (Not-a-Number).

How does Math.sign() handle zero and negative zero?

  • Math.sign(0) returns 0.
  • Math.sign(-0) returns -0

What are common use cases for the Math.sign() method?

  • Determining the Sign of a Number: Using Math.sign() to quickly determine whether a number is positive, negative, or zero.
  • Mathematical and Algorithmic Implementations: Implementing functions and algorithms that need to distinguish between positive and negative values or handle zero and negative zero differently.

How does Math.sign() handle special numeric values like NaN, Infinity, and -Infinity?

  • Math.sign(NaN) returns NaN.
  • Math.sign(Infinity) returns 1.
  • Math.sign(-Infinity) returns -1.

Next Article

Similar Reads

three90RightbarBannerImg