What’s the purpose of Symbol([description]) in ES6? I am reading Mozilla docs and I didn't find any clarifications on the usage of Symbol in ES6. It just explains that Symbol creates a new symbol every time even if the string is unique.
I use it to hide stuff in objects I still want to access but which should be hidden from users, which seems the intended use (read MDN for more info)
Example:
var sym = new Symbol();
module.exports[sym] = 'Haha, no one can see me :)';
I used this kind of thing in my application host's config module module:
Mev-Rael
Executive Product Leader & Mentor for High-End Influencers and Brands @ mevrael.com
Symbols are really hard to understand at the beginning, so I will try to explain in a very simple way by providing real world examples.
Example 1 - no more conflicts with many 3rd party libraries
element.addEventListener('click', handler)and you create a functionaddEvent()which will, let say, store all the handler functions in a custom property of that element, let say,element.handlers..handlersand now we have a conflict (collision), everything broken up.element.[Symbol()]Example 2 - define how JavaScript operators like
instanceofworks yourself1 + 2could do because in C++ you can define how + should work.instanceof,for .. inand some others. This list is updated and currently there is very bad browser support for that.In Google Chrome open the console and paste this code:
const MyComponent = { create() { return { test() { console.log('test') } } }, [Symbol.hasInstance](instance) { return typeof instance.test === 'function' } }const obj = MyComponent.create()and now you can callif (obj instanceof MyComponent).newor custom methods for that anymore.TypeError: invalid 'instanceof' operand MyComponentanymore.Example 3 - private properties or methods
MyPaginator.currentPageproperty which shouldn't be easily accessed from the outside and used only within internal object methods. If modified from outside everythjing can be broken now.Object.keys()for example.There is a very good article I would strongly recommend to read - Metaprogramming in ES6: Symbols and why they're awesome
Another good article - ES6 in Depth: Symbols
Symbols are still badly supported and in most cases impossible to polyfill. Because of that in current world I wouldn't recommend to use them, except simple Symbol() properties on objects if you don't care about IE.