Reputation: 11888
By reading the MDN web doc about undefined
here, I have read
The global undefined property represents the primitive value undefined.
Why is it done that way?
null
is simply a value, why did they create a global property?
Upvotes: 0
Views: 105
Reputation: 6491
Their conversion to boolean is the same:
!!undefined === !!null
however they are there to serve different purposes, undefined itself is a primitive:
typeof undefined; //undefined
typeof null: //object
Null arose from the need to address the last chain in prototypical inheritance:
var obj = new function(){return this};
Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(obj))); //constructor's prototype --> Object.prototype --> null
Beside many functions inherited from Node
or Element
or HTMLElement
prototype is expected to return an object
, when they cannot find, they return null
to hint that they were expected to give you an object, but found nothing instead:
document.getElementById("thiswontbethere"); //null
Undefined on the other hand is generally preferred for uninitialized values:
var obj = {};
obj.someKey //undefined;
Array.apply(null,Array(3)); //[undefined, undefined, undefined]
And undefined does not have to be global, however if you do:
Object.getOwnPropertyDescriptor(window,"undefined");//{value: undefined, writable: false, enumerable: false, configurable: false}
So obviously you cannot change the property descriptor, nor the value itself, but the memory allocation is done on a lower layer, so this is a vendor implementation. It didn't have to be global.
I somehow feel like this a rant question, and you asked it not for it to be answered but to confirm indirectly that js has some "bad design" elements in it.
Upvotes: 1
Reputation: 664640
The why appears to be lost in time - you will have to ask Brendan Eich about it.
It's just one of the many quirks surrounding null
and undefined
that null
is a keyword (literal expression to be precise, that can't be used as an identifier) while undefined
is not. That's the way it is now, and given that many scripts on the web use undefined
as a local variable name, it's too late to do anything about it. (At least ES5 made the global undefined
non-writable).
Upvotes: 2