redrah
redrah

Reputation: 1204

Are ES2015 Symbols appropriate in place of Strings as unique constant values?

I was aware that Symbols had been added to ES2015 but hadn't read up much about them. I've now done a bit of reading and their purpose is apparently not what I'd thought. It seems the intended purpose is to provide a way of creating private attributes. My understanding was that it was something similar to an atom in some functional languages, which is backed up here. I find it odd that it completely fails to mention what I had incrorrectly assumed was the main reason for them, which was in providing a more meaningful alternative to Strings for pattern matching:

export const FOO = 'This value is irrelevant as long as its unique';
// or
export const FOO = Symbol('A sensible description of what foo represents');

switch(blah):
    case FOO: do_something();
    ...

In the above case using Symbol seems to have a number of advantages in that it protects against accidental collisions (i.e. making two constants equal to the same string), removes the burden of coming up with a unique string every time and provides a clear indication to anyone who reads the code about its intended purpose. The last consideration relies to some degree on other people agreeing on my interpretation of what a Symbol should be used for though.

Anyway the question is, is this a good use case for Symbols and if not why not?

Upvotes: 2

Views: 63

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074248

It seems the intended purpose is to provide a way of creating private attributes.

No, not at all. Very, very early on that was one motivator, but it was discarded long before the spec was completed. If they were meant to provide some kind of privacy, we wouldn't have Object.getOwnPropertySymbols.

Private instance information has had a long and tortured path, and is still winding its way through that; currently it's part of the Class Fields proposal (having previously been its own thing).

Anyway the question is, is this a good use case for Symbols and if not why not?

Yes. One of the primary purposes of Symbol is to provide unique identifiers without collision.

From §4.3.25 - Symbol value:

primitive value that represents a unique, non-String Object property key

And from §6.1.5 - The Symbol Type:

Each possible Symbol value is unique and immutable.

Granted that doesn't speak to motivations, but it's indicative.

Upvotes: 5

Related Questions