DEV Community

Cover image for Silly Javascript, says true when asked if (0 == -null); here's why...
Shahzada Fahad Ashraf
Shahzada Fahad Ashraf

Posted on

Silly Javascript, says true when asked if (0 == -null); here's why...

JavaScript is a versatile programming language known for its flexibility, but this flexibility sometimes leads to interesting behaviors.

For instance, try running the following code in your dev console.

Console Screenshot

Strange, right? Well, JavaScript behaves this way due to a concept called type coercion.

Type Coercion

Type coercion is the automatic conversion of one data type to another, often performed in JavaScript during operations involving different types. The loose equality operator (==) triggers type coercion, attempting to make the operands comparable.

In the given expression, the left operand is the number 0, while the right operand involves coercing null to a number. When null is coerced to a number, it results in the value 0. Therefore, the expression essentially becomes 0 == 0.

This outcome might seem surprising at first glance, as one might expect the comparison to be false due to the explicit difference between 0 and -0. However, it is essential to recognize that -null is not equivalent to negative zero but rather zero.

But, why exactly?

Understanding the mechanics behind this behavior requires insight into JavaScript's type coercion rules. The language attempts to find a common type between the operands, prioritizing numeric values. In this case, the coercion of null to a number yields 0, aligning both sides of the equality check.

While this behavior may be convenient in certain scenarios, it highlights the importance of caution when using loose equality (==) in JavaScript. Developers often prefer the strict equality operator (===), which compares both value and type, avoiding unexpected type coercion and promoting more predictable code.

Conclusion

The expression 0 == -null in JavaScript showcases the language's type coercion mechanisms. Through automatic conversion, JavaScript aligns the operands by coercing null to a number, resulting in the equality check 0 == 0. This example serves as a reminder of the nuanced aspects of JavaScript's loose equality operator and the importance of understanding type coercion for writing robust and predictable code.

Top comments (0)