Home > Web Front-end > JS Tutorial > Why Does ` 0 === -0` Evaluate to True in JavaScript, While `Object.is(-0, 0)` Returns False?

Why Does ` 0 === -0` Evaluate to True in JavaScript, While `Object.is(-0, 0)` Returns False?

Linda Hamilton
Release: 2024-11-22 07:04:11
Original
513 people have browsed it

Why Does ` 0 === -0` Evaluate to True in JavaScript, While `Object.is(-0,  0)` Returns False?

The Difference and Equality of 0 and -0

The ECMAScript 5.1 specification distinguishes between 0 and -0, raising the question of why 0 === -0 evaluates to true.

IEEE 754 Standard

JavaScript employs the IEEE 754 standard for representing numbers. According to IEEE 754, signed zero allows for positive zero ( 0) and negative zero (-0). This distinction is required for floating-point arithmetic, as 1/-0 = -∞ and 1/ 0 = ∞.

Strict Equality Comparison Algorithm

Despite the technical distinction, section 11.9.6 of the specification explicitly defines the behavior of the strict equality comparison algorithm for 0 and -0:

  • If x is 0 and y is -0, return true.
  • If x is -0 and y is 0, return true.

Logical and Practical Rationale

Logically, it makes sense to treat 0 and -0 as equal. Distinguishing between them would complicate code, especially when working with zero.

Object.is Comparison Method

ES2015 introduced Object.is for more precise comparisons. Object.is explicitly distinguishes between 0 and -0:

Object.is(-0, +0); // false
Copy after login

The above is the detailed content of Why Does ` 0 === -0` Evaluate to True in JavaScript, While `Object.is(-0, 0)` Returns False?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template