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.
// ONLINE-RUNNER:browser;
console.log( Math.sign( -0 ) ); // +0
console.log( Math.sign( +0 ) ); // -0
console.log( Math.sign( -1 ) ); // -1
console.log( Math.sign( +1 ) ); // +1
console.log( Math.sign( -100 ) ); // -1
console.log( Math.sign( +100 ) ); // +1
console.log( Math.sign( -Infinity ) ); // -1
console.log( Math.sign( +Infinity ) ); // +1
console.log( Math.sign( NaN ) ); // NaN
1. Documentation
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.
2. Polyfil method example
// ONLINE-RUNNER:browser;
// Polyfil method
if (!Math.sign) {
Math.sign = function(x, y) {
if (x === 0 || x !== x) {
return x;
}
return x > 0 ? 1 : -1;
};
}
// Example:
console.log( Math.sign( -0 ) ); // +0
console.log( Math.sign( +0 ) ); // -0
console.log( Math.sign( -1 ) ); // -1
console.log( Math.sign( +1 ) ); // +1
console.log( Math.sign( -100 ) ); // -1
console.log( Math.sign( +100 ) ); // +1
console.log( Math.sign( -Infinity ) ); // -1
console.log( Math.sign( +Infinity ) ); // +1
console.log( Math.sign( NaN ) ); // NaN