模板字符串
Template literals use backticks, evaluate ${...} at runtime, and preserve line breaks. We use { guest: "lida", drink: "tea", extras: ["mint", "lemon"] }.
Start with interpolation
${...} is evaluated at runtime and inserted into surrounding text.
const order = { guest: "lida", drink: "tea", extras: ["mint", "lemon"] };
const label = `${order.guest} ordered ${order.drink}`;
console.log(label);
Evaluate expressions
Expressions such as .length and .join(", ") are evaluated inside ${...}.
This prints 2 extras: mint, lemon; literal text and expressions have different roles.
const order = { guest: "lida", drink: "tea", extras: ["mint", "lemon"] };
const summary = `${order.extras.length} extras: ${order.extras.join(", ")}`;
console.log(summary);
The note has exactly Guest: lida and Drink: tea on separate lines.
Process pieces with a tag
A tagged template receives literal strings and evaluated values.
const order = { guest: "lida", drink: "tea", extras: ["mint", "lemon"] };
const note = `Guest: ${order.guest}
Drink: ${order.drink}`;
console.log(note);
Show the result on a page
The page combines the guest, drink, and extras count.
Show the result on a page
The page combines the guest, drink, and extras count.
<p id="result"></p>
<script>
const order = { guest: "lida", drink: "tea", extras: ["mint", "lemon"] };
document.getElementById("result").textContent =
`${order.guest} ordered ${order.drink} / ${order.extras.length} extras`;
</script>
The visible text is exactly lida ordered tea / 2 extras.
function upper(strings, ...values) {
return strings.reduce((out, text, i) => out + text + (values[i] ?? "").toUpperCase(), "");
}
const order = { guest: "lida", drink: "tea", extras: ["mint", "lemon"] };
const tagged = upper`Guest: ${order.guest}.`;
console.log(tagged);
This lesson has the 5-code, 6-quiz, 1-table shape of spread-rest, but focuses on strings and interpolation.
This final comparison keeps the literal words separate from the evaluated order values.
Run the examples in order and compare each output with the stated fact.
The page message combines the same order object without changing its values.
📊 Template literal pieces
| Part | Meaning | Example |
|---|---|---|
| Backticks | Start and end the template literal | ` text ` |
| Literal text | Copied into the result | ordered |
${expression} |
Evaluated at runtime and inserted | ${order.guest} |
| Source newline | Preserved in the resulting string | A line break between words |
Try it yourself
Change order.drink to "coffee", add ${order.extras.join(", ")}, and create a two-line note.
Common mistakes
Use backticks for interpolation, keep ${ and } paired, and remember that text outside the braces is not JavaScript.
Key point
Backticks delimit the string; ${...} inserts evaluated values; source line breaks remain in the result.
🧠 测试您的知识
测试您的知识
通过这个互动测验挑战自己,看看你对这个主题的理解程度如何
📝 说明
- 仔细阅读每个问题
- 为每个问题选择最佳答案
- 您可以随时重新参加测验
- 您的进度将显示在顶部