Template literals — interpolation, multi-line strings, and tags¶
Level: 101 · for anyone who has glued strings together with a plus sign
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: ${x} converts with the string hint and "" + x with the default hint, so an object whose valueOf returns 1 and toString returns "two" gives "two" in a template and "1" after +; a symbol makes a template throw where String(symbol) works.
Keywords: template literal, ${...}, backtick
What the finished page will answer¶
- Why does an object whose
valueOfreturns1andtoStringreturns"two"give"two"in a template and"1"with"" + x? - What do
${[1, 2]},${{}},${null}and${undefined}produce? - Why does
${Symbol("id")}throw aTypeErrorwhenString(Symbol("id"))works, and what doestscsay about it? - Which newlines and which indentation does a multi-line template keep?
- What does a tag function receive, and why is
\unicodea syntax error in a plain template but allowed afterString.raw?
Examples it will need¶
-
template_literals_conversion_js.js— one object withvalueOfandtoStringinterpolated, concatenated and passed toString(), then arrays,nullandundefinedinterpolated, then a symbol caught as aTypeError -
template_literals_multiline_js.js— a multi-line template inside an indented function, shown withJSON.stringifyso the kept newlines and spaces are visible -
template_literals_symbol_tserror.ts— tsc's TS2731 diagnostic for interpolating a symbol, which suggests wrapping it inString(...)
See also¶
- ToPrimitive — the string and default hints behind the two conversions
- The
+operator — why"" + xasksvalueOffirst - Tagged templates — what a tag function receives, and
String.raw - Template literal types — the same backtick syntax in a type position
- Python: String literals ↗ — the f-strings of Python, and its other literal prefixes
- Rust: The format mini-language ↗ — in Rust, formatting uses a mini-language instead of interpolated expressions