As mentioned in the topic JS the Good Parts seems to claim that a property value can't be undefined. However if you do the following in Chrome's console for example:
var foo = {}
foo.bar = undefined
foo
Then click to expand the foo object you can still see that foo contains a property called bar with the value undefined. Of course from the Javascript side you can't tell the difference between foo.bar returning undefined and foo.unexistingproperty returning undefined. But what is the point of the console still clinging to the property that was set to undefined?
There's a difference between a property existing and being undefined and a property not existing, so Chrome is being sensible here. If you assign a value to a property then the property fundamentally exists in that object. One difference is that a property that has been explicitly set to be undefined will show up in a for...in
loop:
var foo = {};
foo.bar = undefined;
// The following will alert "bar"
for (var i in foo) {
alert(i);
}
Another is that "bar" in foo
will return true
, as will foo.hasOwnProperty("bar")
.
Technically, undefined is a valid value to assign to a variable. It does make a difference albeit usually not useful:
var foo = {
bar: undefined
};
foo.hasOwnProperty("bar"); // returns true
foo.hasOwnProperty("bat"); // returns false
Also:
for (var n in foo) {
console.log(n, foo[n]); // should log "bar" and "undefined"
}
I personally would follow the advise given by Crockford in this case. Assigning undefined
as a value can lead to confusing code and should therefore be considered bad. It surprises people not expecting it.
We already have null
to use for this purpose which is less confusing to future maintainers. Let undefined
really mean not defined and use null
to mean not known.
Remember that when reading Crockford's book you're reading advice on best practices and opinion on how javascript should work according to him. How javascript actually works is a different matter altogether (and according to him not necessarily good).
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