Languages
[Edit]
EN

JavaScript - how to check is zero positive (+0) or negative (-0)?

7 points
Created by:
Root-ssh
6266

Using JavaScript it is possible to check if zero is positive or negative in following way.

1. Positive / negative zero test example

// ONLINE-RUNNER:browser;

console.log(      0 ==  0     ); // true
console.log(     -0 == -0     ); // true
console.log(     -0 == +0     ); // true

console.log( 1 / +0 == 1 / +0 ); // true
console.log( 1 / -0 == 1 / -0 ); // true
console.log( 1 / -0 == 1 / +0 ); // <--- false

console.log(      0 ===      0 ); // true
console.log(     -0 ===     -0 ); // true
console.log(     -0 ===     +0 ); // true

console.log( 1 / +0 === 1 / +0 ); // true
console.log( 1 / -0 === 1 / -0 ); // true
console.log( 1 / -0 === 1 / +0 ); // <--- false

Explaination: typical programmer do not think about kind of zero. To avoid computation mistakes JavaScript returns true during -0 and +0 comparision. In practise sommteims it is neccessary to make more complicated computation that requires more precised results like close to 0 on left or right site of axis (OX axis). This is reasone why -0 and +0 have been intorduced - it gives information how 0 has been computed. The way how to check if zero is positive or negative is based on some trick: 1 / -0 = -Inf; 1 / +0 = +Inf; -Inf != +Inf; +Inf = +Inf; -Inf = -Inf;

2. Alternative way to make zero test example

// ONLINE-RUNNER:browser;

console.log( Object.is(  0,  0 ) ); // true
console.log( Object.is( -0, -0 ) ); // true
console.log( Object.is( -0, +0 ) ); // false

Note: this approach has been introduced in ECMAScript 2015 (ES6).

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

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.
Rockstar community members
Thank you for great work 👍