Languages
[Edit]
EN

JavaScript - Math.sign() method example

10 points
Created by:
AnnLen
9180

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

SyntaxMath.sign(number)
Parametersnumber - integer or float number value (primitive value).
Result

Returns -1, -0, +0, +1, NaN for negarive, negative zero, positive zero, positive numbers.

If operation can not be executed it returns NaN.

Descriptionsign 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

 

JavaScript - Math (EN)

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join