</> Code Corner

JavaScript · JS Tutorial · Lesson 16

JS String Templates

Template literals with ${ } interpolation.

Template literals use backticks (`) and allow variables and expressions inside ${...}.

Example

<p id="demo"></p>
<script>
let firstName = "John";
let price = 10, vat = 0.25;
let total = `Total: ${(price * (1 + vat)).toFixed(2)}`;
let header = "Templates";
let tags = ["template literals", "javascript", "es6"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) { html += `<li>${x}</li>`; }
html += `</ul>`;
document.getElementById("demo").innerHTML = `Welcome ${firstName}!<br>${total}${html}`;
</script>
Tip: This is called string interpolation. Template literals also keep line breaks.

Keep reading “JS String Templates”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋