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?
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.