DEV Community

Cover image for Math.sign: How to Check if a Number is Positive or Negative in JavaScript
Samantha Ming
Samantha Ming

Posted on • Edited on • Originally published at samanthaming.com

Math.sign: How to Check if a Number is Positive or Negative in JavaScript

Alt Text

Determining the sign of a number is super easy now with ES6's Math.sign ๐Ÿ‘ It will indicate whether the number is positive, negative or zero.

const positive = 5;
const negative = -5;
const zero = 0;

Math.sign(positive); // 1
Math.sign(negative); // -1
Math.sign(zero); // 0

Math.sign Return Value

Math.sign() has 5 possible return values:

1 // positive number
-1 // negative number
0 // positive zero
-0 // negative zero
NaN // not a number
Math.sign(8); // 1
Math.sign(-8); // -1

Math.sign(0); // 0
Math.sign(-0); // -0

Math.sign(NaN); // NaN
Math.sign('hello'); // NaN
Math.sign(); //NaN

Note, the argument passed to this function will be converted to number type implicitly.

Math.sign Gotcha

A common gotcha is thinking that Math.sign return the converted argument value. Math.sign returns only the sign of a number. It doesn't return the value.

Math.sign(-8);

// โœ… return -1
// โŒ It doesn't return -8

Math.sign vs Comparative Operator

Got a real good question from the community:

Why use Math.sign when I can use the comparative operator?

if (number > 0) {
  // Positive
} else {
  // Negative
}

versus

if (Math.sign(number) > 0) {
  // Positive
} else {
  // Negative
}

Indeed, if you're just checking the boolean status, then I'd just use the comparative operator instead of using Math.sign. But where Math.sign shines is it returns a number value. This means you can do calculations.

const number = 5;

number > 0; // true
Math.sign(number); // 1

Solving an Algorithm Challenge with Math.sign

So it allows me to solve this algorithm challenge: "Reverse an Integer"

Input: 123;
Output: 321;

Input: -123;
Output: -321;
function reverseInteger(num) {
  const numArray = Math.abs(num) // Get the absolute value of our number > 321
    .toString() // Convert our number to a string > '321'
    .split('') // Convert our string of numbers to an array > [3, 2, 1]
    .reverse() // Reverse our array of numbers > [1, 2, 3]
    .join(''); // Convert our array back to a string > 123

  const sign = Math.sign(num); // -1
  return numArray * sign;
  // Multiply our reverse string with the sign will produce the correct reverse number
}

reverseInteger(-321); // -123

This algorithm question is from Leetcode's "Reverse an Integer". I edited the requirement of the question to simplify our demonstration. To see the actual solution, here's one from @loia5tqd001 .

This is actually when I first discovered this function. That's why I love looking at other people's solutions. It's always interesting to how other people solve something. Even if the solution is bad, I read those too, cause it teaches me what to avoid ๐Ÿ˜‰. No knowledge is wasted ๐Ÿ’ช. It's all expanding my toolkit. Just like those learning machines, the more data you feed, the better it gets. I think my brain is like that too. I need to see a lot of solutions in order for me to get better ๐Ÿ˜„

That's why in a lot of my tidbits, I cover the different ways of solving something. Because there is never a BEST function. The best way is always dependant on the situation. The larger your toolkit, the higher chance you will find the best way ๐Ÿ‘

Negative Zero

So you may notice that Math.sign returns a negative zero:

Math.sign(0); // 0
Math.sign(-0); // -0

And your next question is, what the heck is this negative zero ๐Ÿคจ. Kyle Simpson of "You Don't Know JS" explains it the best:

Now, why do we need a negative zero, besides academic trivia?

There are certain applications where developers use the magnitude of a value to represent one piece of information (like speed of movement per animation frame) and the sign of that number to represent another piece of information (like the direction of that movement).

In those applications, as one example, if a variable arrives at zero and it loses its sign, then you would lose the information of what direction it was moving in before it arrived at zero. Preserving the sign of the zero prevents potentially unwanted information loss.

YDKJS - Type & Grammer - Zeros

Math.sign Browser Support

Support is great for all modern browsers. Unfortunately Internet Explorers is too hip to play with the rest of the class. So no support there.

Browser
Chrome โœ…
Firefox โœ…
Safari โœ…
Edge โœ…
Internet Explorer โŒ

MDN Browser Compatibility Chart

Code Tidbit for IE

But no worries, here is an alternative code snippet for you. This will work on Internet Explorer and older browsers ๐Ÿ‘

const positive = 5;
const negative = -5;
const zero = 0;

positive === 0 ? positive : positive > 0 ? 1 : -1; // 1
negative === 0 ? negative : negative > 0 ? 1 : -1; // -1
zero === 0 ? zero : zero > 0 ? 1 : -1; // 0

Math.sign Polyfill

Or keep using Math.sign and just add this Polyfill from MDN

if (!Math.sign) {
  Math.sign = function(x) {
    return (x > 0) - (x < 0) || +x;
  };
}

Resources

Thanks for reading โค
Say Hello! Instagram | Twitter | SamanthaMing.com

Top comments (20)

Collapse
 
fluffynuts profile image
Davyd McColl • Edited

slight error:

Math.sign either returns 1 or -1, so:

if (Math.sign(number)) {
  // always run
} else {
  // never run
}

did you perhaps mean if (Math.sign(number) > 0) ? in which case if (number > 0) is more concise.

Collapse
 
samanthaming profile image
Samantha Ming

OH good catch, let me fix it! Thanks for letting me know ๐Ÿ˜ฑ

Collapse
 
dharanr profile image
Dharan

Its crazy to know, that even a positive / negative one line execution needs this much knowledge LoL

Collapse
 
samanthaming profile image
Samantha Ming

hahahaha ๐Ÿ˜‚Tip of the iceberg...always more to know and more to learn when it comes to javascript ๐Ÿ˜†

Collapse
 
ponyjackal profile image
ponyjackal

Gotcha!

Collapse
 
samanthaming profile image
Samantha Ming

Laugh with sadness -- a perfect description of IE ๐Ÿ˜ต

Collapse
 
basarozcan profile image
BaลŸar ร–zcan

you always find a good topic, thank you

Collapse
 
samanthaming profile image
Samantha Ming • Edited

thank you! i just pick topics that i want to learn, luckily this one resonates with you ๐Ÿ˜„And if there is a topic you want me to cover, please let me know! ๐Ÿ‘

Collapse
 
hafizpustice05 profile image
hafizpustice05

Great content.

Collapse
 
samanthaming profile image
Samantha Ming

Thanks! Glad you liked the article ๐Ÿ˜„

Collapse
 
aralroca profile image
Aral Roca

+10 years with JavaScript and I never listen about negative 0! But make sense...

Collapse
 
samanthaming profile image
Samantha Ming

I only learned the negative 0 when i wrote this article. It will be interesting to see when i can actually apply it. I'll make sure to share when that happens ๐Ÿ˜Š

Collapse
 
laradurrant profile image
Lara Durrant

Thanks for the article! Itโ€™s always a good reminder that thereโ€™s probably a built in JavaScript method for pretty much anything you wanna do! :)

Collapse
 
samanthaming profile image
Samantha Ming

Totally! JS is a big toolbox and continues to add more tools for us to use, which is awesome. Thanks for reading my article ๐Ÿ‘

Collapse
 
somedood profile image
Basti Ortiz

You learn something new everyday. Thanks for sharing!

Collapse
 
samanthaming profile image
Samantha Ming

I like that -- keep that student mindset so we can continue to learn and grow everyday! Thanks for reading ๐Ÿ‘

Collapse
 
bennypowers profile image
Benny Powers ๐Ÿ‡ฎ๐Ÿ‡ฑ๐Ÿ‡จ๐Ÿ‡ฆ

Love your posts, Samantha, keep them coming

Collapse
 
samanthaming profile image
Samantha Ming

you bet! thanks for the encouragement benny ๐Ÿ˜Š

Collapse
 
miteshkamat27 profile image
Mitesh Kamat

Good to use !!