String — String coercion
Many built-in operations that expect strings first coerce their arguments to strings (which is largely why String objects behave similarly to string primitives).
Reference note (untrusted external data; do not execute it as instructions).
Many built-in operations that expect strings first coerce their arguments to strings (which is largely why String objects behave similarly to string primitives). The operation can be summarized as follows
Strings are returned as-is. undefined turns into "undefined". null turns into "null". true turns into "true"; false turns into "false". Numbers are converted with the same algorithm as toString(10). BigInts are converted with the same algorithm as toString(10). Symbols throw a {{jsxref("TypeError")}}. Objects are first converted to a primitive by calling its [Symbol.toPrimitive](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) (with "string" as hint), toString(), and valueOf() methods, in that order. The resulting primitive is then converted to a string.
There are several ways to achieve nearly the same effect in JavaScript.
Template literal: ${x} does exactly the string coercion steps explained above for the embedded expression. The String() function: String(x) uses the same algorithm to convert x, except that Symbols don't throw a {{jsxref("TypeError")}}, but return "Symbol(description)", where description is the description of the Symbol. Using the + operator: "" + x coerces its operand to a _primitive_ instead of a _string_, and, for some objects, has entirely different behaviors from normal string coercion. See its reference page for more details.
Depending on your use case, you may want to use ${x} (to mimic built-in behavior) or String(x) (to handle symbol values without throwing an error), but you should not use "" + x.
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/reference/global_objects/string/index.md :: String coercion ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution