SyntaxStudy
Sign Up
JavaScript Template Literals In Depth
JavaScript Intermediate 8 min read

Template Literals In Depth

Template Literals In Depth

Template literals, introduced in ES2015, are string literals delimited by backtick characters. They solve two long-standing pain points in JavaScript: embedding variable values into strings and writing multi-line strings without concatenation or escape sequences.

Expression Interpolation

Inside a template literal, any expression wrapped in ${ } is evaluated and its result is coerced to a string and inserted. This includes arithmetic, method calls, ternary expressions, and even nested template literals.

Multi-line Strings

A template literal preserves newlines and indentation exactly as written in the source file. This makes building HTML snippets or formatted output much cleaner than joining strings with \n.

Tagged Templates

A tagged template is a function call where the function receives the string parts and interpolated values as separate arguments. Tags power libraries like styled-components, GraphQL query builders, and localisation utilities. The tag function can return any value, not just a string.

Example
const user = 'Bob';
const score = 95;
const msg = "Player " + user + " scored " + score + " points.";
const better = `Player ${user} scored ${score} points.`;
console.log(better);
const html = `
  <div class="card">
    <h2>${user}</h2>
    <p>Score: ${score}</p>
  </div>
`;
console.log(html);
function highlight(strings, ...vals) {
  return strings.reduce((acc, str, i) =>
    acc + str + (vals[i] !== undefined ? `<b>${vals[i]}</b>` : ''), '');
}
console.log(highlight`Hello ${user}, score: ${score}`);
Pro Tip

Tagged templates are underused — consider them whenever you need to sanitise HTML, translate strings, or build domain-specific languages inside JavaScript.