So after a big argument/debate/discussion on the implementation of null and undefined in javascript I'd like somebody to explain the reasoning behind the implementation and why they differ in some circumstances. Some particular points I find troubling:
null == undefined
evaluates to true
null + 1
equals 1 but undefined + 1
equal NaN
if(!null)
evaluates to true and if(null)
evaluates to false but null == false
evaluates to false.I've read the specification and I know how the results are reached, I'm looking for the paradigms and reasons that dictate this being the specification. Some of these points, especially the second one, given the first, feel very inconsistent.
Difference Between undefined and nullundefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.
The value null represents the intentional absence of any object value. It's never assigned by the runtime. Meanwhile any variable that has not been assigned a value is of type undefined . Methods, statements and functions can also return undefined .
Thus, it makes sense that null does not strictly equal undefined . But, and this may surprise you, null loosely equals undefined . In JavaScript, a double equals tests for loose equality and preforms type coercion. This means we compare two values after converting them to a common type.
The short and sweet version is that JavaScript was designed and implemented very rapidly by the Netscape team, and it had some inconsistencies such as the ones that you've pointed out.
The Internet Exploder team did its best to copy JS exactly and they did a damn good job of it to the point that the inconsistencies were copied as well. When Netscape went to get JS standardized as ECMAScript MS was a part of it and basically said that they weren't allowed to change the standard because it would break old code (existing systems inertia). The inconsistencies were standardized and that was that.
Douglas Crockford has a very good series of talks about some of these issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With