Sometimes we wants to know the sign of a number, it is a trivial task, but require us to write some logic in order to get it done.
1
2
3
const num = -8;
// Old Way
num === 0 ? num : (num > 0 ? 1 : -1); // -1
Determining the sign of a number is super easy with modern ES6’s Math.sign()
.
1
2
3
4
5
6
7
8
9
10
11
12
console.log(Math.sign(3));
// expected output: 1
console.log(Math.sign(-3));
// expected output: -1
console.log(Math.sign(0));
// expected output: 0
console.log(Math.sign('-3'));
// expected output: -1
Mat.sign()
accepts one parameter, If it is not a number, it is implicitly converted to one.
The
Math.sign()
function returns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. If the number passed intoMath.sign()
is 0, it will return a +/- 0. Note that if the number is positive, an explicit (+) will not be returned.
Examples
1
2
3
4
5
6
7
8
9
10
Math.sign(4); // 1
Math.sign(-4); // -1
Math.sign('-2'); // -1
Math.sign(0); // 0
Math.sign(-0); // -0 what the heck is negative zero?
Math.sign(NaN); // NaN
Math.sign('bar'); // NaN
Math.sign(); // NaN
Negative Zero
JavaScript implements the IEEE Standard for Floating-Point Arithmetic (IEEE 754), which has signed zeroes. Positive zero (+0)
is the same as unsigned zero (0)
, but negative zero (-0)
is a different value, but behaves similarly.
“Why do we need negative zero?”
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.
You Don’t Know JS by Kyle Simpson