Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

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

0 contributions
7 points

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).

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