點燈坊

失くすものさえない今が強くなるチャンスよ

Using Symbol to Add Object Property

Sam Xiao's Avatar 2021-11-27

If we want to add Object property at runtime, it chanced that we override property of original Object. Since Symbol is a unique value, using Symbol Property to prevent property from overriding.

Version

ECMAScript 2015

Override Property

let obj = {
  name: 'Tom'
}

obj.name = 'Sam'
obj.name // ?

We want to add name property dynamically, but we will override the original name property if the property exists.

prop000

[]

let obj = {
  name: 'Tom'
}

let name = Symbol ()
obj [name] = 'Sam'

obj.name // ?
obj [name] // ?
  • Since Symbol is an unique value, so we can use Symbol as property name to ensure not to override existing property
  • We have to use [] to add Symbol property

prop001

Object Spread

let obj = {
  name: 'Tom'
}

let name = Symbol ()
obj = {
  ...obj, 
  [name]: 'Sam'
}

obj.name // ?
obj [name] // ?

We can also use ... to spread original object first and [] to add Symbol property.

prop002

Object.defineProperty

let obj = {
  name: 'Tom'
}

let name = Symbol ()
Object.defineProperty (obj, name, { value: 'Sam' })

obj.name // ?
obj [name] // ?

We can also use Object.defineProperty to add Symbol property.

Conclusion

  • We can’t use . to add Symbol property; the result is undefined