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
- MDN Web Docs - Math.sign()
- Stack Overflow: Number sign in JavaScript
- Leetcode Solution: Reverse an integer
- Math.sign MDN Polyfill
- Stack Overflow: How to check the value given is a positive or negative integer?
- Stack Overflow: JS Negative Number
- Originally published at www.samanthaming.com
Thanks for reading ❤
Say Hello! Instagram | Twitter | SamanthaMing.com
Top comments (20)
slight error:
Math.sign
either returns 1 or -1, so:did you perhaps mean
if (Math.sign(number) > 0)
? in which caseif (number > 0)
is more concise.OH good catch, let me fix it! Thanks for letting me know 😱
Its crazy to know, that even a positive / negative one line execution needs this much knowledge LoL
hahahaha 😂Tip of the iceberg...always more to know and more to learn when it comes to javascript 😆
Gotcha!
you always find a good topic, thank you
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! 👏
Great content.
Thanks! Glad you liked the article 😄
+10 years with JavaScript and I never listen about negative 0! But make sense...
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 😊
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! :)
Totally! JS is a big toolbox and continues to add more tools for us to use, which is awesome. Thanks for reading my article 👏
You learn something new everyday. Thanks for sharing!
I like that -- keep that student mindset so we can continue to learn and grow everyday! Thanks for reading 👏
Love your posts, Samantha, keep them coming
you bet! thanks for the encouragement benny 😊
Checks browser support
Be happy that is wide supported
Read the IE line
Laugh with sadness
By the way, cool tip!
Laugh with sadness -- a perfect description of IE 😵
Good to use !!