I am looking for information on the difference between acceptable variable names in JavaScript, when they are key names in an object versus when the variables are referenced declaratively.
For example:
in an object, I can do this:
var obj = {
'##A': 1,
'@B': 2,
'C*': 3
};
however, we cannot reference those variables in the code, as this will be some form of syntax error
of course, we cannot do this:
obj.##A++; //syntax error
obj.@B++; //syntax error
obj.C*++; //syntax error
and we definitely cannot do this either:
var ##A = 1; //syntax error
var @B = 2; //syntax error
var C* = 3; //syntax error
I believe the primary difference is that the key of object can take any value of a JS Symbol. Whereas a variable name cannot take any value of Symbol.
So this is a two part question:
- How is this disparity described in JavaScript? What was the motivation to have the disparity between Symbol's being valid key names but not valid variable names?
- Is there a publicly available regex that can validate a JS variable name? I want to run this regex against keys of a particular object. The reason is that users of a library that I am writing will define variable names with the keys from an object, and they could easily use Symbol characters that would be invalid JS variable names.
To be more specific, this is for a dependency injection facility.
The end-user defines dependencies like so:
const deps = {
'request': function(){
return require('request'); //useless, but as a simple example
},
'users': function(){ //no problems here
return db.users.find({});
},
'users-older-than-13': function(){ //invalid because of "-" chars
return db.users.find({age: {gt: 13}});
}
};