EN
JavaScript - Math.sign() method example
13 points
Math
sign
is static method that takes only one parameter and returns number that represents its signum.
xxxxxxxxxx
1
console.log( Math.sign( -0 ) ); // +0
2
console.log( Math.sign( +0 ) ); // -0
3
console.log( Math.sign( -1 ) ); // -1
4
console.log( Math.sign( +1 ) ); // +1
5
console.log( Math.sign( -100 ) ); // -1
6
console.log( Math.sign( +100 ) ); // +1
7
console.log( Math.sign( -Infinity ) ); // -1
8
console.log( Math.sign( +Infinity ) ); // +1
9
console.log( Math.sign( NaN ) ); // NaN
Syntax | Math.sign(number) |
Parameters | number - integer or float number value (primitive value). |
Result |
Returns If operation can not be executed it returns |
Description | sign is static method that takes only one parameter and returns number that represents its signum. |
Note: this method has been added in ECMAScript 2015.
xxxxxxxxxx
1
// Polyfil method
2
if (!Math.sign) {
3
Math.sign = function(x, y) {
4
if (x === 0 || x !== x) {
5
return x;
6
}
7
8
return x > 0 ? 1 : -1;
9
};
10
}
11
12
// Example:
13
14
console.log( Math.sign( -0 ) ); // +0
15
console.log( Math.sign( +0 ) ); // -0
16
console.log( Math.sign( -1 ) ); // -1
17
console.log( Math.sign( +1 ) ); // +1
18
console.log( Math.sign( -100 ) ); // -1
19
console.log( Math.sign( +100 ) ); // +1
20
console.log( Math.sign( -Infinity ) ); // -1
21
console.log( Math.sign( +Infinity ) ); // +1
22
console.log( Math.sign( NaN ) ); // NaN