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?
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.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) orSymbol.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.While there is no convention for naming symbol-holding variables (yet), there certainly is a convention for naming symbols themselves:
Symbol
). Of course, they're still unique anyway, so you basically can use whatever name you want.@@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)"
).