Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

JavaScript - Math.sign() method example

0 contributions
10 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

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more