Javascript Symbol data type are primitive values.
Symbol instances are unique and immutable.
A symbol can be a unique identifier for object properties that does not risk property collision.
Symbols are instantiated using the Symbol function.
typeof operator will identify a symbol as symbol.
let sym = Symbol(); console.log(typeof sym); // symbol
Symbol()
function can have an optional string used for identifying the symbol instance when debugging.
The string you provide is separate from the symbol's identity:
let genericSymbol = Symbol(); let otherGenericSymbol = Symbol(); let fooSymbol = Symbol('foo'); let otherFooSymbol = Symbol('foo'); /* ww w .ja v a2s.c om*/ console.log(genericSymbol == otherGenericSymbol); console.log(fooSymbol == otherFooSymbol); // false
Symbols do not have a literal string syntax.
let genericSymbol = Symbol(); console.log(genericSymbol); // Symbol() // w w w.j a v a 2 s. co m let fooSymbol = Symbol('foo'); console.log(fooSymbol); // Symbol(foo);
The Symbol function cannot be used with the new keyword.
let mySymbol = new Symbol(); // TypeError: Symbol is not a constructor
To use an object wrapper, make use of the Object()
function:
let mySymbol = Symbol(); let myWrappedSymbol = Object(mySymbol); console.log(typeof myWrappedSymbol); // "object"