Languages
[Edit]
EN

JavaScript - Math.sign() method example

13 points
Created by:
Dexter
510

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

Alternative titles

  1. JavaScript - Math.sign() documentation with examples
  2. js - Math.sign() method documentation with examples
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - Math.sign()

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join