ResourcesJavascriptGuides

Template Literals

Introduction

Template literals are a new and powerful way to handle strings in JavaScript. They provide a cleaner and easier to read syntax for string interpolation, multi-line strings, and more.


Template Literals

Previous String Concatenation Method

Before ES6 and Template Literals in order to combine strings we would do this:

const name = 'Alice';
const greeting = 'Hello, ' + name + '!';
 
console.log(greeting); // Output: Hello, Alice!

Let's explore now, what Template literals do.

Syntax

Template literals use backticks ()instead of quotes and allow embedded expressions using$`.

Basic example

const name = 'Alice';
const greeting = `Hello, ${name}!`;
 
console.log(greeting); // Output: Hello, Alice!

Multi-line Strings

Template literals make it easy to create multi-line strings without using escape characters.

const multiLine = `This is a string
that spans multiple
lines.`;
 
console.log(multiLine);

Embedded Expressions

Template literals support embedding any valid Javascript expression.

const a = 5;
const b = 10;
const sum = `The sum of a and b is ${a + b}.`;
 
console.log(sum); // Output: The sum of a and b is 15.

Tagged Template Literals

Tagged template literals allow you to parse template literals with a function.

function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => `${result}${str}<strong>${values[i] || ''}</strong>`, '');
}
 
const name = 'Alice';
const age = 25;
const message = highlight`My name is ${name} and I am ${age} years old.`;
 
console.log(message); // Output: My name is <strong>Alice</strong> and I am <strong>25</strong> years old.

Template Literals in HTML

Template literals can be used to create HTML templates dynamically.

const title = 'Hello, World!';
const content = 'This is a dynamic HTML content.';
const html = `
  <div>
    <h1>${title}</h1>
    <p>${content}</p>
  </div>
`;
 
document.body.innerHTML = html;

CSS in Template Literals

Template literals can also be used with CSS-in-JS libraries to define styles dynamically.

const primaryColor = 'blue';
const styles = `
  .button {
    background-color: ${primaryColor};
    color: white;
    padding: 10px;
    border: none;
    border-radius: 5px;
  }
`;
 
const styleSheet = document.createElement('style');
styleSheet.type = 'text/css';
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);

Resources

MDN Web docs

On this page