The good perk of having a lot of people who code around you is that you end up discussing things that you don't get to see on a day-to-day basis as a simpleton frontend developer.
What is a Symbol?
Let's imagine that we have an object where we store a person's
id and their
If we want to access the value of the
id property, we'd just do:
It is fair to assume that
id won't change as often as the other characteristics of a person, and tailor our work around that assumption.
Let's try to use a symbol as a key by creating it. This can be done using the
You could, in theory, use no
"id" parameter (properly referred as descriptor), but if you were to use more than one symbol key, it'd be more challenging to know which is which.
Why symbols then?
Using symbols as object keys will provide you with a unique and guaranteed way of accessing object properties, even if other code adds or modifies properties with the same key.
Some other code, for whatever reason, will try to do
You will be left with
The symbol key is allowing us to preserve the original value even if some other code might try to alter the property
With symbols you can add private properties to an object that are not intended to be modified or accessed directly by other code.
But beware! Symbols keys are not enumerated, which means that they do not show up in the list of keys of the object if you try to access them by loops and mappings.
You will need to be aware of the structure of your object and if you need to access the symbol keys, you'll have to use
getOwnPropertySymbols() (Opens in a new tab).