Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a convention for naming symbols in ES6?

I'm toying around with ES6, looking at symbols. Unlike ruby for example where you'd write :symbol, ES6 symbols seem to be allowed any "standard" variable name. To be honest I am finding this rather confusing:

var privateProperty = Symbol();
var obj = {};
obj[privateProperty] = 'some value goes here';

as it tends to make me think that privateProperty is probably a plain string like the years before. Using :privateProperty is not valid.

So just like using $bar for a jQuery object or bar$ for a RxJS/Bacon stream, I was wondering if there is already an established convention for naming symbols in ES6?

like image 256
m90 Avatar asked Jul 11 '15 12:07

m90


1 Answers

obj[privateProperty] = …; tends to make me think that privateProperty is probably a plain string like the years before.

Well, that's the old thinking that we will need to forget. privateProperty is a key, which can be either a string (property name) or symbol. Similarly, we already have learned to distinguish (integer) indices from "normal" properties.

ES6 seems to allow any "standard" variable name

Just as does Ruby. The difference is that ES6 doesn't introduce a literal notation for symbols (which resolve to the same thing), but allows them to be created only by using Symbol (locally) or Symbol.for (globally).

There is no standard convention for naming variables that hold symbol values.
Of course, you can always use hungarian notation if you tend to want such type annotations. If I had to coin a standard, I'd propose to use a more subtle leading underscore (var _myPrivate). Underscores in property names had always implied something special, and it would look similar for computed property keys (obj[_myPrivate]) then.

Is there a convention for naming symbols in ES6?

While there is no convention for naming symbol-holding variables (yet), there certainly is a convention for naming symbols themselves:

  • local symbols should have a very descriptive descriptor string (given as an argument to Symbol). Of course, they're still unique anyway, so you basically can use whatever name you want.
  • global symbols need to avoid collisions. The convention is to namespace them appropriately, and connect those namespace names with dots - like a Java package name. If the symbol is available as a global variable, its descriptor should have the same name (similar to the builtin, native symbols, which are like @@iterator = Symbol.for("Symbol.iterator");). If the symbol is exported by a module or library, its descriptor should be prefixed with the module/library name (to avoid collisions).

And it would probably be a best practise to use the same name for the variable (like the native symbols already do, Symbol.iterator.toString() == "Symbol(Symbol.iterator)").

like image 160
Bergi Avatar answered Oct 22 '22 02:10

Bergi