Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
256 views
Welcome To Ask or Share your Answers For Others

1 Answer

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...