Codectionary / Developer documentation / JavaScript

Template Literals

Template literals, introduced in ES6, use backticks (`) instead of quotes and allow embedded expressions via ${expression} syntax, along with genuine multi-line strings without needing escape characters. They largely replace manual string concatenation with + for building dynamic strings.

Syntax

`text ${expression} more text`

Examples

String Interpolation

Embedding variables and expressions directly inside a string.

const name = "Alice";
const age = 25;

// Old way
console.log("Hello, " + name + "! You are " + age + " years old.");

// Template literal way
console.log(`Hello, ${name}! You are ${age} years old.`);

// Expressions work too, not just variables
console.log(`Next year you will be ${age + 1}.`);

Multi-line Strings

Writing strings that span multiple lines without escape characters.

const message = `This is line one.
This is line two.
This is line three.`;

console.log(message);

// Useful for building small HTML snippets too
const html = `<div class="card">
  <h2>${name}</h2>
  <p>Age: ${age}</p>
</div>`;

Best practices

  • Prefer template literals over string concatenation with + for anything involving variables
  • Use them for multi-line strings instead of manually inserting \n characters
  • Keep embedded expressions simple - move complex logic out into a variable before interpolating it
  • Remember template literals are still just strings - they do not automatically escape HTML, which matters for security when inserting user input into the DOM

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation