Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Symbols not convert string implicitly

Tags:

javascript

Why Symbol('test').toString() works well, but I can't use '' + Symbol('test')?

It will throw Error:

cannot convert a Symbol value to a string

Why does the implicit type conversion not work? Why is the code not equal to '' + Symbol('test').toString()?

like image 949
SkyAo Avatar asked Jun 08 '17 03:06

SkyAo


2 Answers

According to ECMA-262, using the addition operator on a value of type Symbol in combination with a string value first calls the internal ToPrimitive, which returns the symbol. It then calls the internal ToString which, for Symbols, will throw a TypeError exception.

So calling the internal ToString is not the same as calling Symbol.prototype.toString.

So I guess the answer to:

Why does the implicit type conversion not work?

is "because the spec says so".

like image 123
RobG Avatar answered Sep 23 '22 00:09

RobG


You can, however you're not meant to do so by accident.

console.log(''+String(Symbol('My symbol!')))
// Symbol(My other symbol!)

console.log(Symbol('My symbol!').description)
// My other symbol!

console.log(Symbol.keyFor(Symbol.for('My other symbol!')))
// My other symbol!    

Note: Symbol.keyFor only works for symbols created via the Symbol.for function.

Symbol.keyFor(Symbol('My symbol!')) will evaluate to undefined.

You can also use .description to get the string value used to create the symbol.

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/keyFor
like image 23
John Leidegren Avatar answered Sep 22 '22 00:09

John Leidegren