Reputation: 3698
I am learning Es6: Symbols. I am playing with it and trying to create a symbol using another symbol as description:
var s = Symbol('foo');
console.log(s.toString()); //"Symbol(foo)"
var sS = Symbol(s); // <- thorws error
var sF = Symbol.for(s); // <- thorws error
console.log(s, sA);
I am not able to understand why is it not letting me use existing symbol as description. When I run the code above I see following console error:
Uncaught TypeError: Cannot convert a Symbol value to a string
at Function.for (native)
As the error says that it can not convert the symbol to string. But as you see in code(line 2), by using toString()
function I am able to convert the symbol in string. Can anyone please elaborate what's going on? Thanks.
Upvotes: 2
Views: 110
Reputation: 664444
why is it not letting me use existing symbol as description
Simply because all descriptions must be strings, nothing else.
the error says that it can not convert the symbol to string, but by using
toString()
I am able to convert the symbol in string
Yes, you can explicitly cast a symbol to a string and get its description by using the toString
method. But all implicit conversions throw exceptions - this is a deliberate feature to prevent us from accidentally using the non-unique description instead of the symbol, e.g. when doing string concatenation with a property key.
Upvotes: 4