Languages
[Edit]
EN

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

7 points
Created by:
Root-ssh
175460

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

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