1

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:

  1. 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?
  2. 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}});
  }


};
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Object property keys are arbitrary strings. Identifiers are restricted. Restricting the characters that can be used in identifiers is generally a requirement to simplify parsing. – Pointy Mar 08 '16 at 19:25
  • Why do you need JS variable names for everything? There's no disparity; JS arrays take arbitrary strings as their keys, and JS code follows JS syntax. – Dave Newton Mar 08 '16 at 19:25
  • Key names can be a string, as well as unaccepted characters in variable name present in keys can be accessed via bracket notation only. It cannot be accessed via dot notation. – Rajaprabhu Aravindasamy Mar 08 '16 at 19:26
  • 3
    you can still use `obj['##A']++;` – Nina Scholz Mar 08 '16 at 19:28
  • 1
    http://stackoverflow.com/questions/1661197/what-characters-are-valid-for-javascript-variable-names This describes it and has a validator. – kemiller2002 Mar 08 '16 at 19:29
  • Thanks Kevin, I think Anthony Mills answer makes the most sense for me, since I want to validate variable names, not object identifiers? So it's just a simple case of starts with $, _, or a-z, etc. – Alexander Mills Mar 08 '16 at 19:38

0 Answers0