How do template literals insert values into JavaScript strings?
Quick answer
Put a template literal in backticks and write ${expression} where you want a value inserted. JavaScript evaluates the expression, converts its result to a string, and places it in the surrounding text. For example, with const n = 3, ` Value: ${n * 2} becomes Value: 6. In single or double quotes, ${n * 2}` is ordinary text, not an expression. [S1]
The question, the details, the next step.
A practical checklist
Check whether the string starts and ends with backticks or ordinary quotes.
For a backtick string, identify each
${...}placeholder.Evaluate each placeholder expression using the values in the example.
Convert each result to text and join it with the unchanged surrounding characters.
Write the complete resulting string, including spaces and punctuation.
A few more useful answers
Do I include the braces in the inserted output?
No. In an ordinary untagged template literal, ${...} marks where the expression goes; the expression's string value is inserted, not the placeholder punctuation. [S1]
Can a template literal span more than one line?
Yes. Template literals can include line breaks in their source code. [S1] The examples above focus on inserting values into one-line strings.
Will every template literal produce a string?
The simple substitution explanation applies to ordinary, untagged template literals. A tagged template calls a tag function, which may return something other than a string. [S1]
Sources
References used for this guide.
- [S1] Template literals (Template strings) — JavaScript | MDN developer.mozilla.org · Checked
