Why does Javascript the Good Parts claim that “a property value can be any Javascript value other than undefined”?

As mentioned in the JS thread, Good Parts seem to argue that the value of a property cannot be undefined. However, if you follow these steps in the Chrome console, for example:

var foo = {} foo.bar = undefined foo 

Then click to expand the foo object, which you can still see that foo contains a property called bar with the value undefined. Of course, from Javascript's side, you cannot tell the difference between returning foo.bar undefined and foo.unexistingproperty returning undefined. But what is the point of the console that is still clinging to a property set to undefined?

+4
source share
3 answers

undefined is a Javascript way of telling you that a value does not exist, and does not throw an error when accessing a property without a try / catch block. Although technically what Chrome shows is incorrect in the Crockford account, it is at least logical; the property exists, although as undefined .

If you want to delete a property, you can use the delete operator:

 delete foo.bar; 
+3
source

There is a difference between the existing and the former undefined and the missing property, so Chrome is reasonable here. If you assign a value to a property, then the property basically exists in this object. One of the differences is that a property that is explicitly set to undefined will be displayed 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 , like foo.hasOwnProperty("bar") .

+7
source

Technically, undefined is a valid value for assigning a variable. It really matters, although this is 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 will follow the recommendations given by Crockford in this case. Assigning undefined as values ​​can lead to code confusion and therefore should be considered bad. This surprises people not expecting this.

We already have null to use for this purpose, which less confuses future maintainers. Let undefined really mean that it is not defined, and use null to denote the unknown.

Remember that while reading Crockford's book, you read tips on best practices and opinions on how javascript should work in accordance with it. How javascript actually works is a completely different matter (and, according to him, not necessarily a good one).

+4
source

All Articles