Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding a variable whose name leads with a numeric value

Tags:

javascript

I noticed that if I try to create an object with a key name that leads with a numeric value, an error is thrown (which goes along with JavaScript naming outlined here: What characters are valid for JavaScript variable names?). However, I noticed that I can still add such a variable name dynamically if I do so

Fails:

object.1foo = "bar";

Fails:

object = {
  1foo: "bar"
}

Succeeds:

object["1foo"] = bar;

Why is that?

like image 501
stinkycheeseman Avatar asked Dec 22 '11 13:12

stinkycheeseman


3 Answers

When you do object["1foo"] you are actually escaping the name of the property, so that's why it works.

The other too fail because 1foo isn't escaped, it's in the same form.

If you want to access object members with standard dot notation (eg. object.property) you aren't allowed to use any special characters besides _ or $; Aside from that, the name cannot start with a number. For all other cases you are forced to use square brackets and quotation marks to access object elements.

like image 108
alessioalex Avatar answered Oct 21 '22 05:10

alessioalex


How identifiers are formed is a syntactic rule, that is, it only applies when the source of your program is being parsed. At run time, object fields' names are just arbitrary strings, and the engine does not care if these strings are "valid" from the parser's point of view:

obj = {}

obj["foo"] - ok
obj["1xx"] - ok
obj["{{{"] - ok
obj["   "] - ok
like image 33
georg Avatar answered Oct 21 '22 04:10

georg


When accessing object["1foo"] you are not creating an identifier but a key to look up a value inside your object.

Identifiers cannot begin with a digit, keys don't have any such specifications (of kind of "obvious" reasons.

Identifiers are not values, keys (in the sense described in this post) are not identifiers.

When doing {"1foo": 123} you are not making 1foo a proper identifier, it's a rvalue variable of type string.


According to the ECMA standard

7.6 Identifier Names and Identifiers

Identifier ::

  • IdentifierName but not ReservedWord

IdentifierName ::

  • IdentifierStart
  • IdentifierName, IdentifierPart

IdentifierStart ::

  • UnicodeLetter
  • $
  • _
  • \ UnicodeEscapeSequence

IdentifierPart ::

  • IdentifierStart
  • UnicodeCombiningMark
  • UnicodeDigit
  • UnicodeConnectorPunctuation
  • <ZWNJ>
  • <ZWJ>

...

11.1.5 Object Initializer

PropertyName [can be any of the following]:

  • IdentifierName
  • StringLiteral
  • NumericLiteral
like image 2
Filip Roséen - refp Avatar answered Oct 21 '22 04:10

Filip Roséen - refp