In the book Javascript the good parts, on the opening page of Ch3 on objects, it states:
An object is a container of properties, where a property has a name and a value. A property name can be any string, including the empty string. A property value can be any Javascript value except for undefined.
Note: undefined is highlighted in the book to denote that is is a literal.
In practice, however, I am able to do it.
var a = { "name": undefined };
What is wrong with my understanding ?
I believe the answer is that he's wrong.
As you observe, you can set var a = { "name": undefined };
.
a.name === undefined
a.name === a.someFakeProperty
Here's where they're different, though:
'someFakeProperty' in a === false
'name' in a === true
Or, to do it a different way,
a.hasOwnProperty('someFakeProperty') === false
a.hasOwnProperty('name') === true
Using the somewhat infamous for..in
loop,
for (var i in a) {
alert(i);
}
... will give you name
.
So, by value you may not be able to distinguish undefined and undefined
, but they are quite different internally.
Addition: he's wrong about the property names, too - As noted in the comments, property names are cast to string so I was wrong about this bit.a[window] = 43; a[window] == 43;
is just fine. Sure, you can't then do a.window
, but a.___
is just syntactic sugar for a['___']
.
I don't like the terminology that Crockford uses, he seem to mix the concept of undefined
and undeclared.
The statement:
A property value can be any Javascript value except for undefined.
Is completely wrong IMO, because undefined
is a primitive value of the language.
See also:
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