Great reply! Another thing i'd like to add is that Symbols are useful to avoid accidental overrides when developing a library that can be extended by 3rd party plugins.
Imagine we have the following extensible library:
export default { x: 1, y: 2, usefulMethod() { return this.x; }, extend(property, value) { Object.defineProperty(this, property, { value }) }, register(plugin) { plugin(this) } }
And the following 3rd party plugin
export default (MyLib) => { MyLib.extend('x', 2); }
You can consume it like this
import MyLib from 'mylib' import MyPlugin from 'myplugin' MyLib.register(MyPlugin); MyLib.usefulMethod() // returns 2 instead of 1
As you can see, the plugin replaced the value of x. If we never want that to happen we can protect our keys with Symbols:
const _x = Symbol('x') const _y = Symbol('y') export default { [_x]: 1, [_y]: 2, usefulMethod() { return this[_x]; }, extend(property, value) { Object.defineProperty(this, property, { value }) }, register(plugin) { plugin(this) } }
Now the properties we don't want to get modified are safe while the whole object can be extended at will.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Great reply!
Another thing i'd like to add is that Symbols are useful to avoid accidental overrides when developing a library that can be extended by 3rd party plugins.
Imagine we have the following extensible library:
And the following 3rd party plugin
You can consume it like this
As you can see, the plugin replaced the value of x. If we never want that to happen we can protect our keys with Symbols:
Now the properties we don't want to get modified are safe while the whole object can be extended at will.