Strings written with backticks ` instead of quotes have superpowers: you can drop variables and expressions straight into the text, and they can span multiple lines. They go by several names (template strings, template literals, string templates), all meaning the same thing. Added in ES6 (2015), they are now the standard way to build any string that includes values.
` is the key in the top-left corner, just below Esc, sharing a key with ~. It is not the apostrophe ' key.
let text = `Hello World!`;
On its own, that is just a normal string. The difference shows up in three places: quotes, line breaks, and ${ }.
Because the string is wrapped in backticks, single and double quotes inside it need no escaping at all:
let text = `He's often called "Johnny"`;
console.log(text);
Only a backtick inside a template needs escaping: `Use the \` key`.
With quotes, you need \n for a line break, and pressing Enter mid-string is an error. With backticks, just press Enter:
let text = `The quick
brown fox
jumps over
the lazy dog`;
console.log(text);
This is the big one. Inside a template string, ${ } is a slot: JavaScript works out whatever is inside it and drops the result into the text. This is called interpolation.
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
console.log(text);
Compare the same sentence built with +. The template version reads like the final sentence, with no juggling of quotes, spaces, and plus signs:
let name = "Sam";
let score = 42;
let msg1 = "Player " + name + " scored " + score + " points.";
let msg2 = `Player ${name} scored ${score} points.`;
console.log(msg1);
console.log(msg2);
${ } is just text. "Hello ${name}" logs exactly Hello ${name}, dollar sign and all. If your placeholders are showing up literally, check that the string uses backticks, not quotes.
You are not limited to variable names. Any expression works inside ${ }: math, method calls, even a ternary.
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
console.log(total);
let qty = 3;
console.log(`${qty} item${qty === 1 ? "" : "s"}`);
console.log(`Shouting: ${"hello".toUpperCase()}`);
(toUpperCase() is a string method from the next lesson.) Remember the plural trick from the Ternary lesson, which needed extra parentheses when built with +? Inside ${ } the ternary is already neatly boxed off, so the precedence trap cannot happen.
`$${price}` the first $ is just a dollar sign in the text, and the second starts the slot. `Cost: $${9.99}` gives Cost: $9.99.
Template strings are ideal for building chunks of HTML from data. Combined with a loop, they can turn a list into a web page list:
let header = "Template Strings";
let tags = ["template strings", "javascript", "es6"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
html += `<li>${x}</li>`;
}
html += `</ul>`;
console.log(html);
Put that string into a page element with innerHTML (shown in Function Invocation) and the browser shows a heading and a bulleted list. Add a fourth tag to the array and the list grows automatically.
<script> tag, and the browser would run it. That attack is called cross-site scripting (XSS). Build HTML from your own data only, or clean user text first.
What does this log?
let pet = "Rex";
console.log("Good dog, ${pet}!");
Good dog, ${pet}!, exactly as written. The string uses double quotes, so ${ } is plain text. Swap the quotes for backticks to get Good dog, Rex!.With let a = 4, b = 5;, which line logs 4 + 5 = 9?
console.log(`${a} + ${b} = ${a + b}`);console.log(`a + b = a + b`);console.log(`${a + b} = ${a} + ${b}`);console.log("${a} + ${b} = ${a + b}");4, 5, and 9. B has no slots, so it logs the letters. C logs 9 = 4 + 5. D uses quotes, so the ${ } parts are just text.Which is not a feature of template strings?
\n' and " inside without escaping${ }toUpperCase() is for. The other three are exactly what backticks add.${ } with math and $${ } for the price${ } to print "1 message" or "5 messages"+=, then log it