Nathaniel D. Waggoner
Nathaniel D. Waggoner

Reputation: 2886

When is a JavaScript Property NOT an Identifier?

I'm reading this article: http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/.

Which makes the following statement:

Just like when looking up properties, if the property you are defining is an identifier, you can use dot syntax instead of bracket syntax. For instance, you could say man.sex = "male" in the example above.

I looked up identifiers in JavaScript because I was a little confused on this statement and found this article: http://coderkeen.com/old/articles/identifiers-en.html. It says:

An identifier is regarded as a value which is unique in relation to all the other identifiers in a system.

and later:

Javascript makes no exclusion and identifiers are used for:

Variable names Function names Names of formal parameters of functions

As the title implies:

When would I end up with a property of a JavaScript object which wasn’t an identifier and could thus not be accessed using the . syntax? Or am I misreading something?

Upvotes: 1

Views: 549

Answers (2)

Bergi
Bergi

Reputation: 665122

I looked up identifiers in JavaScript because I was a little confused on this statement and find this:

An identifier is regarded as a value which is unique in relation to all the other identifiers in a system.

The dot syntax does refer to identifiers as a syntax element, as they are specified in EcmaScript 5 §7.6. It means they must not contain whitespaces or punctuation marks, for example.

While "foo-bar x" can be used as a property name of an object, you cannot access it via dot syntax obj.foo-bar x because it would be ambigous. You need to use bracket notation obj["foo-bar x"] instead.

Another common example are array indices. Technically they're just properties of the Array object as well, just as .length is. However, as integers are no identifiers (which must not begin with a digit) you cannot write arr.0 but have to use arr[0].

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324760

var someobject = {};
someobject["I'm a turtle"] = true;

I'm a turtle is most definitely not an identifier!

Upvotes: 3

Related Questions