Convert JavaScript character to string?

ES6 has .toString() on Symbol , which returns a string representation of Symbol , but I wonder why '' + Symbol() does not work (running this expression raises a TypeError , which I don't expect)? Is the latter just a call to .toString() on the new Symbol and adds ( + ) it to an empty string?

+6
source share
2 answers

Is the latter just a call to .toString() on a new Symbol and adds ( + ) it to an empty string?

No, in fact, characters cannot be implicitly passed into strings or numbers, although, strangely enough, you can implicitly attribute them to a logical one.

MDN has a section on some of these traps:

Character Type Conversions

Some things to consider when working with character type conversion.

  • If you try to convert a character to a number, a TypeError value will be selected (for example, +sym or sym | 0 ).
  • When using the free equality, Object(sym) == sym returns true.
  • Symbol("foo") + "bar" throws a TypeError (cannot convert a character to a string). This does not allow you, for example, to create a new string property name from a character.
  • The conversion is β€œsafer” String(sym) works like calling Symbol.prototype.toString() with characters, but note that new String(sym) will produce.

This behavior is described in the specification in the abstract ToString operation :

Argument Type: Symbol

Result: Throw a TypeError exception.

And similarly for the abstract ToNumber operation :

Argument Type: Symbol

Result: Throw a TypeError exception.

To convert a Symbol to a string without a TypeError , you must use either the ToString method or String() .

+8
source

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toString .

The Symbol object overrides the toString method of the Object; it does not inherit Object.prototype.toString (). For Symbol objects, the toString method returns a string representation of the object.

+1
source

Source: https://habr.com/ru/post/1012853/


All Articles