Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null vs. undefined and their behaviour in JavaScript

Tags:

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.

like image 724
Endophage Avatar asked Aug 09 '11 18:08

Endophage


People also ask

What is the difference between undefined and null in JavaScript?

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.

Why JavaScript has null and undefined?

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 .

Does null equal undefined JavaScript?

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.


1 Answers

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.

like image 193
zzzzBov Avatar answered Oct 12 '22 02:10

zzzzBov