Re:ES6 in Depth: Symbols (2015)
by masklinn on Wednesday July 12, 2017 @08:56AM
(#14752077)
> In JavaScript they are used for metadata and other things you don't want to be serialized by JSON.stringify() or Object.assign().
They're used to avoid conflicts for "generic method" hooks (similar to dunder methods in Python): the conflict issues is why environments have broken when new methods were added, and why e.g. Object.keys and their ilk are "static" functions rather than methods.
If you don't want JSON.stringify or Object.assign to see your properties just make them non-enumerable e.g.:
Object.assign will copy symbol-keyed properties. In fact Symbol-keyed properties are enumerable by default.
They live in an odd half-way world because many constructs only accept/handle string-keyed properties: Object.keys/entries/values and JSON.stringify use EnumerableOwnProperties and (for..in) uses EnumerateObjectProperties, both of which are specified to ignore non-string-keyed properties (before even checking for enumerability).
> I've always been confused by why Ruby uses symbols so much.
They're used to avoid conflicts for "generic method" hooks (similar to dunder methods in Python): the conflict issues is why environments have broken when new methods were added, and why e.g. Object.keys and their ilk are "static" functions rather than methods.
If you don't want JSON.stringify or Object.assign to see your properties just make them non-enumerable e.g.:
Object.assign will copy symbol-keyed properties. In fact Symbol-keyed properties are enumerable by default.They live in an odd half-way world because many constructs only accept/handle string-keyed properties: Object.keys/entries/values and JSON.stringify use EnumerableOwnProperties and (for..in) uses EnumerateObjectProperties, both of which are specified to ignore non-string-keyed properties (before even checking for enumerability).
> I've always been confused by why Ruby uses symbols so much.
Mutable non-interned strings.