Values and variables

A guide to JavaScript Template Literals

Learn how JavaScript template literals create multiline strings, interpolate expressions with ${}, handle escaping, and pass string parts and values to tag functions.

8 minute lesson

~~~

What are template literals?

Template literals are JavaScript literals delimited by backticks:

const message = `Hello`

They were added in ES2015 and provide three main features:

  • multiline strings
  • interpolation with ${...}
  • tagged templates

The MDN template literals reference documents their complete syntax.

Multiline strings

A quoted string needs an escape sequence for a new line:

const message = 'First line\nSecond line'

A template literal can contain the line break directly:

const message = `First line
Second line`

Whitespace inside the backticks is part of the string. Indentation is preserved too:

const message = `
  First line
  Second line
`

Use .trim() when you intentionally start and end on separate lines but do not want those outer line breaks:

const message = `
First line
Second line
`.trim()

Interpolation

Put an expression inside ${...} to include its value:

const name = 'Flavio'
const message = `Hello, ${name}`

message //'Hello, Flavio'

Any JavaScript expression can go inside the placeholder:

const price = 10
const quantity = 3

const message = `Total: ${price * quantity} euro`

The expression is evaluated, then its result is converted to a string.

Escaping special syntax

Escape a backtick with a backslash:

const message = `Use the \`const\` keyword`

Escape ${ when you want those characters to appear literally:

const message = `Write \${name} to interpolate a value`

Tagged templates

A tagged template calls a function with the template’s static strings and expression values.

The function name goes directly before the template:

const language = 'JavaScript'
const message = highlight`I am learning ${language}.`

This is not a normal function call with one finished string. JavaScript calls highlight before joining the parts.

A tag can return a string, an object, a React element, or any other value.

Libraries use tagged templates for tasks such as CSS generation and query construction. The tag function decides what the syntax means.

How a tag function receives values

The first argument contains the static string parts. The remaining arguments contain the evaluated expressions:

function inspect(strings, ...values) {
  console.log(strings)
  console.log(values)
}

const item = 'book'
const price = 20

inspect`The ${item} costs ${price} euro`

In this example, strings contains three parts:

['The ', ' costs ', ' euro']

And values contains:

['book', 20]

Here’s a small tag that surrounds every interpolated value with markers:

function mark(strings, ...values) {
  let result = strings[0]

  for (let i = 0; i < values.length; i++) {
    result += `**${values[i]}**${strings[i + 1]}`
  }

  return result
}

const topic = 'template literals'
const message = mark`Learn ${topic} today`

message //'Learn **template literals** today'

Tagged templates do not automatically escape unsafe input. Security depends on what the tag function does.

Raw strings

The strings array has a raw property containing text before escape sequences are processed.

JavaScript also provides String.raw, a built-in tag that returns the raw form:

const path = String.raw`C:\Users\Flavio`

path //'C:\\Users\\Flavio'

Lesson completed