1 min read
Symbol is on of the primitive data types of JavaScript. It's definitely the least used and one of the strangest primitives of JavaScript. When a symbol is created its value is kept privately. Two symbols who have the same value would never be equal to each other. So the name collision is not a thing you should worry about using symbols.
You can create the symbols as follows:
const s = Symbol();
const s2 = Symbol('hello');
const s3 = Symbol('hello');
Even though the values are the same Symbol('hello') and Symbol('hello') are not equal.
Symbol() === Symbol() //false
Symbol('hello') === Symbol('hello') // false
You can use symbols in objects as object properties. Their names would never collide. This way the property cannot be overwritten accidentally by a user or you.
Even after using Symbol() for defining our properties, Object.keys() or Object.getOwnPropertyNames() results would not show the properties created using Symbol() method. But they are accessible using Object.getOwnPropertySymbols() method.
I encourage you to go deeper and read the documentation on MDN.
Ilker AkbiyikTable of Contents