DEV Community

Discussion on: What is the Symbol in JavaScript?

Collapse
 
reegodev profile image
Matteo Rigon

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.