Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does crockford mean when he says that undefined cannot be a property value?

Tags:

javascript

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 ?

like image 681
Frankie Ribery Avatar asked Nov 15 '10 04:11

Frankie Ribery


2 Answers

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 - 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['___']. As noted in the comments, property names are cast to string so I was wrong about this bit.

like image 144
Chris Morgan Avatar answered Oct 20 '22 05:10

Chris Morgan


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:

  • Difference between undefined and not being defined in Javascript
like image 29
Christian C. Salvadó Avatar answered Oct 20 '22 06:10

Christian C. Salvadó