Languages
[Edit]
EN

JavaScript - Math.sign() method example

10 points
Created by:
AnnLen
1771

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)

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.