|
|
|
|
|
by Arnavion
4192 days ago
|
|
In addition to the other replies, Symbols were at one point meant to be used for implementing private visibility in classes - the idea being that the private fields of an object would only be visible inside the class closure, preventing external code from being able to access them. However, private has been backed off from ES6 now. |
|
The feature which symbols offer is unforgeable contracts. These offer some benefits of type systems and module systems (AKA existential type systems). Any time we want to restrict access to some value, we can "seal" it by generating a new symbol and using that as its key in an object/mapping. We can pass the symbol to the code we want to "unseal" it, whilst the object itself can get passed around anywhere at all, without anyone being able to extract or replace the value until it reaches the "unsealer".
To see why this would be useful for "private visibility", the trick is not that we're hiding the values to everyone outside our lexical scope (which is trivial, since that's what lexical scope is); it's that we can allow access to these values, via functions which check that they're given the correct symbol. In other words, we can have our code "recognise" when some other code should be given access. If we limit ourselves to making "classes", where the symbol is in-scope in the "constructor" and doesn't leak out, then we have a primitive form of type-checking; if we're given the correct symbol, the other code must be of the same "class", so we might decide to let it see our "privates".
Of course, that's just a degenerate edge-case. There are all kinds of other uses, for example section XII of Harper's Practical Foundations for Programming Languages is dedicated to the topic http://www.cs.cmu.edu/~rwh/plbook/book.pdf