Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "Javascript the Good Parts" claim that "A property value can be any Javascript value except for undefined"?

Tags:

javascript

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?

like image 215
Sam Avatar asked Dec 09 '22 12:12

Sam


2 Answers

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").

like image 147
Tim Down Avatar answered Jan 11 '23 22:01

Tim Down


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).

like image 41
slebetman Avatar answered Jan 12 '23 00:01

slebetman