Math.sign and negative zero in JavaScript
Beginner · 3 min read
Is a number positive, negative or zero? Bank apps ask this to color a balance red or green. Charts ask it to decide whether a bar points up or down. Sorting code asks it to decide which of two items goes first.
JavaScript answers with Math.sign. In this tutorial you will use it on ordinary numbers, and then hunt for the two strange answers it can give that are not -1, 0 or 1. One of them is a value most beginners have never heard of: minus zero.
You only need to know what console.log and === do.
What Math.sign returns
Math.sign(n) returns a number that tells you the sign of n:
1ifnis positive,-1ifnis negative,0ifnis zero.
It never tells you the size. Math.sign(42) and Math.sign(0.001) are both just 1.
Minus zero, in one paragraph
JavaScript numbers follow a standard called IEEE-754, which is how almost every computer stores decimals. That standard has two zeros: 0 and -0. They behave the same in almost every sum, and === says they are equal. The difference only shows up in a few places, and Math.sign is one of them.
Here is the exercise. Try it first if you like, or read on and we will work through it together.
3 The sign of a number, including minus zero
easyReport -1, 0 or 1 for a number's sign. Then find the two answers Math.sign gives that are not any of those three.
Stuck? Three hints, smallest first
- 1.
Math.signreturns a number, not a boolean. - 2. It has five possible results, not three: the two extras are
-0andNaN. - 3.
Object.isis the only way to tell-0from0;===says they are equal.
Step 1: the three everyday answers
console.log(Math.sign(42)); // 1
console.log(Math.sign(-42)); // -1
console.log(Math.sign(0)); // 0
These are the answers everyone expects. Notice they are numbers, not true or false.
Step 2: NaN and text
Math.sign turns its argument into a number first, like the other Math functions.
console.log(Math.sign('5')); // 1
console.log(Math.sign(NaN)); // NaN
console.log(Math.sign('abc')); // NaN
The string '5' becomes the number 5, so the sign is 1. NaN means "Not a Number", and anything that can't become a number gives NaN back. That is the first of the two extra answers.
Step 3: the sign of minus zero
console.log(Math.sign(-0)); // -0
Math.sign(-0) gives back -0. It isn't 0, and it isn't -1. That is the second extra answer, so Math.sign has five possible results in total: 1, -1, 0, -0 and NaN.
Step 4: why === can't see it
The natural next move is to check the result with ===. That's the wrong turn:
console.log(Math.sign(-0) === 0); // true
console.log(Math.sign(-0) === -0); // true
Both are true, because === treats the two zeros as equal. To tell them apart you need Object.is, a stricter comparison:
console.log(Object.is(Math.sign(-0), -0)); // true
console.log(Object.is(Math.sign(-0), 0)); // false
Turning the value into text hides it too. JSON.stringify(-0) gives the string '0', and so does String(-0). So if you only ever print values through JSON, minus zero is invisible.
console.log(JSON.stringify(Math.sign(-0))); // 0
Step 5: where minus zero leaks out
Dividing by it is the place minus zero shows up in a real answer:
console.log(1 / 0); // Infinity
console.log(1 / -0); // -Infinity
The two zeros give opposite infinities. Most code never divides by zero on purpose, but this is why the difference exists at all.
Step 6: sign and abs rebuild the number
Math.sign gives the direction and Math.abs gives the size. Multiply them and you get the original number back:
const rebuild = (n) => Math.sign(n) * Math.abs(n);
console.log(rebuild(-7)); // -7
console.log(rebuild(7)); // 7
This pairing comes back in later exercises, for example when you round a negative number by rounding its size and putting the sign back.
The full solution
The answer panel prints Math.sign for positives, negatives, both zeros, NaN and a string. The checks underneath use Object.is for minus zero, and also show that JSON.stringify prints it as '0'. Press Run to see the output.
console.log('sign(42) :', Math.sign(42));
console.log('sign(-42) :', Math.sign(-42));
console.log('sign(0) :', Math.sign(0));
console.log('sign(-0) :', Math.sign(-0), '<- printed as -0, and === 0 is true');
console.log('sign(NaN) :', Math.sign(NaN));
console.log("sign('5') :", Math.sign('5'), '<- coerced');
console.log('is it -0? :', Object.is(Math.sign(-0), -0));
console.log('JSON sees :', JSON.stringify(Math.sign(-0)), '<- which is why the check uses Object.is');
// sign and abs are complements: together they rebuild the number.
const rebuild = (n) => Math.sign(n) * Math.abs(n);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a positive gives 1', Math.sign(42), 1);
test('a negative gives -1', Math.sign(-42), -1);
test('zero gives zero', Math.sign(0), 0);
test('but -0 gives -0, not 0 and not -1', Object.is(Math.sign(-0), -0), true);
test('=== cannot see the difference', Math.sign(-0) === 0, true);
test('and JSON prints it as 0, so never assert it that way', JSON.stringify(Math.sign(-0)), '0');
test('NaN in, NaN out', Number.isNaN(Math.sign(NaN)), true);
test('sign times abs rebuilds the number', [rebuild(-7), rebuild(7)], [-7, 7]);
test('over a list there are only two non-zero answers', [...new Set([1, 2, 3, -1, -2].map((n) => Math.sign(n)))], [1, -1]);
Math.sign is a comparison shortcut: xs.sort((a, b) => Math.sign(a - b)) reads better than the ternary, and a comparator only cares about the sign anyway.
-0 is the part worth internalising. It exists because IEEE-754 keeps the sign through an underflow, so -0.0001 * 0.0001 eventually reaches -0 rather than 0. It compares equal to 0 with ===, prints as 0 through JSON.stringify, and yet 1 / -0 is -Infinity. That is the one place it can leak into a real answer.
Common mistakes
- Treating the result as a boolean.
Math.sign(-5)is-1, which is "truthy", soif (Math.sign(n))is true for negatives too. Compare it:Math.sign(n) === 1. - Checking for minus zero with
===.-0 === 0istrue. UseObject.is(value, -0). - Forgetting
NaN. Code that handles1,-1and0still has to decide what to do when the input wasn't a number.
Try it yourself
- Write
describeBalance(n)that returns'credit','debit'or'empty'usingMath.sign. - Sort
[5, -2, 9, 0]withxs.sort((a, b) => Math.sign(a - b))and check the order. - Find a multiplication of two ordinary numbers that gives
-0. (Hint: one of them is zero.)