javascriptvue.js

Use a Symbol as an object value in JavaScript


What is the purpose of using a Symbol as a property value in a JavaScript object rather than just a normal value?

For example, in Vue a text VNode has a Symbol as an object value. Why is this, and what are some other use cases for doing such a thing?

const vNode = {
  __v_isVNode: true,
  type: Symbol(v-txt)
}

An h1 in Vue would have this vNode type:

const vNode = {
  __v_isVNode: true,
  type: 'h1'
//      ^^^^ Why not use Symbol(h1)?
}

Solution

  • There are several special types of nodes, Symbol(v-txt) is one of them and represents text node.

    There's no need to treat h1, etc element nodes in a special way; type string values correspond to DOM elements with respective tag names. While text nodes shouldn't be confused with element nodes. type: 'v-txt' or any other non-unique string value would be treated the same way as <v-txt> element, which has to be avoided.

    As the related question explains, ES6 symbols provide unique values on language level, including using them as object keys, which is helpful in this case. This would require to use string tokens like 'TXT_WHATEVER_UNIQUE_KEY', etc as type value in ES5 to unambiguously identify nodes.