Home > Web Front-end > JS Tutorial > Are 0 and -0 Considered Equal in JavaScript?

Are 0 and -0 Considered Equal in JavaScript?

Susan Sarandon
Release: 2024-11-20 14:39:22
Original
994 people have browsed it

Are  0 and -0 Considered Equal in JavaScript?

Are 0 and -0 the Same in JavaScript?

Despite the distinction made in the ECMAScript 5.1 specification, 0 and -0 evaluate to true using strict equality in JavaScript.

Why is this?

JavaScript adopts the IEEE 754 standard for numerical representation. According to this standard, signed zero can exist in two forms: 0 (positive zero) and -0 (negative zero). However, division by 0 or -0 results in ∞ and -∞, respectively, rather than undefined.

Technically, this distinction between 0 and -0 is crucial. However, JavaScript provides an exception in its strict equality algorithm. Section 11.9.6 explicitly states that 0 and -0 are treated as equal in strict equality comparisons.

This exception aligns with the logical notion of treating 0 and -0 as equivalent. Additionally, it simplifies development by eliminating the need to consider this distinction in code.

Note:

ES2015 introduced Object.is as a new comparison method. Unlike the loose and strict equality operators, Object.is expressly distinguishes between 0 and -0:

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

The above is the detailed content of Are 0 and -0 Considered Equal in JavaScript?. 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