After this lesson you can build text from variables without a pile of plus signs, write text that spans several lines, and put small calculations directly inside a sentence.
The old way and the better way
You already know that + joins strings.
const name = "Asha";
const n = 3;
console.log("Hi " + name + ", " + n + " items");That prints Hi Asha, 3 items. It works, but the quotes, spaces and plus signs add up, and one missing space spoils the output. A template literal does the same job more clearly. Wrap the text in backticks (the key under Escape on most keyboards) and put values inside ${ }.
const name = "Asha";
const n = 3;
console.log(`Hi ${name}, ${n} items`); // Hi Asha, 3 itemsThe text reads like the sentence it produces, and the spaces are exactly what you typed.
Any expression works
What goes inside ${ } is not limited to variable names. It can be any expression: arithmetic, a method call, or a condition.
const name = "Asha", n = 3, price = 4.5;
console.log(`Hi ${name}, you have ${n} item${n === 1 ? "" : "s"}. Total: ${(n * price).toFixed(2)}`);
// Hi Asha, you have 3 items. Total: 13.50Here a small test adds an "s" only when needed, and toFixed formats the money. The expression is evaluated, converted to a string, and inserted. Keep what you place inside short. If it needs more than a line, calculate it above, give it a name, and insert the name.
Multi-line strings
A normal string cannot contain a raw line break. A template literal can, and the break becomes part of the text.
const poem = `Roses are red,
Violets are blue.`;
console.log(poem);That prints two lines. This is very useful for blocks of HTML. Be careful with indentation: spaces at the start of the continued lines are part of the string too.
See it work
Change the name, count and price and watch the sentence follow.
<p id="out"></p>
<script>
const customer = "Asha";
const items = 3;
const price = 4.5;
const total = items * price;
const sentence = `${customer} ordered ${items} item${items === 1 ? "" : "s"}.
Total: $${total.toFixed(2)}`;
document.getElementById("out").innerHTML = sentence.replace("\n", "<br>");
</script>Spot the $${total...} near the end: the first $ is a plain dollar sign, and ${ } after it is the placeholder. A $ only starts a placeholder when it is directly followed by {. Also notice that HTML ignores a raw line break, so the example swaps it for a <br> tag to show it.
What gets inserted
Whatever is inside the braces is converted to a string. For numbers and booleans that is what you expect. For other values it can surprise you.
console.log(`${1 + 1} ${"x".toUpperCase()} ${[1, 2, 3]} ${{}} ${null} ${undefined}`);
// 2 X 1,2,3 [object Object] null undefined- An array becomes its items joined by commas.
- A plain object becomes
[object Object], which is almost never what you want. UseJSON.stringify(obj)to see its content. nullandundefinedbecome the wordsnullandundefined. If you seeundefinedin your output, a variable was empty.
Escaping
To show a backtick or the exact characters ${, put a backslash before them.
console.log(`Price: \${5}`); // Price: ${5}
console.log(`back\`tick`); // back`tickA word about tagged templates
You can place a function name directly before a template literal, as in tag followed by a backtick string. The function then receives the pieces and the values separately. This powers some libraries for styling and database queries. It is an advanced feature and you do not need it now.
When to use which
Use a template literal whenever you mix text with values, or need several lines. Use a plain quoted string for a fixed piece of text with no values. Many teams also use plain quotes for short constants and reserve backticks for places where they are needed, so a backtick tells the reader "something is inserted here". Either way, be consistent.
Building pieces of HTML
A frequent use of template literals on the web is making a block of HTML from data. Because the text can span lines and hold values, the code looks very much like the markup it creates. Later in the course you will put such text into a page. One warning for then: if a value comes from a visitor, inserting it as HTML can let them add their own markup, so treat user-supplied text carefully and prefer setting textContent. For now it is enough to know that the same ${ } placeholder that builds a sentence also builds markup, a message for the console, or a line of a report.
Common mistakes
- Using quotes instead of backticks.
"Hi ${name}"prints the placeholder as text. Check the quote character first. - Writing
$nameor{name}. The placeholder needs both the dollar sign and the braces:${name}. - Letting
undefinedappear. If a sentence showsundefined, the variable was never set or the name is wrong. - Putting long logic inside
${ }. It becomes unreadable. Move it to a variable above. - Forgetting indentation is included. In a multi-line literal, leading spaces end up in the output.
- Inserting an object directly.
[object Object]means you needed a property such asuser.name.
Exercise
- Create variables
product,qtyandunitPrice. Print one sentence such as "3 x Notebook = 13.50", built with a single template literal andtoFixed(2). - Make it say "1 item" or "2 items" correctly using a conditional expression inside the placeholder.
- Use a multi-line template literal to make a three-line address, and print it.
Next: Operators.
Key points
- A template literal is text wrapped in backticks that can contain ${expression} placeholders.
- Any expression can go inside ${}, and its result is converted to a string.
- Template literals can span several lines, and the line breaks become part of the text.
- null, undefined, arrays and objects convert in ways that may surprise you, such as [object Object].
- Escape a literal backtick or ${ with a backslash.