javascript-template-literals

Template Literals in JavaScript

  • 4 min

Template Literals are a special syntax for defining text strings in JavaScript, which provides several very powerful advantages over traditional ones.

They were introduced in ECMAScript 6 (2015) and are defined using backticks (`) (instead of single or double quotes).

const greeting = `Hello, world`;  // Template Literal
Copied!

Template Literals provide several very useful features such as,

  • Interpolation of variables and expressions
  • Supporting multiline and formatted text

Template Literals are a very powerful syntax. Get used to using it because it greatly simplifies working with text.

Expression Interpolation

One of the most powerful features of Template Literals is the ability to interpolate variables and expressions directly within the text string.

This is done using the ${expression} syntax inside the template literal. The Template Literal will replace it with its value evaluated as a String.

const name = 'Luis';
const age = 25;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // "Hello, my name is Luis and I am 25 years old."
Copied!

In addition to variables, Template Literals allow including any JavaScript expression within the string (mathematical operations, function calls, conditionals, etc).

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

const isAdult = (age) => age >= 18;
const message = `You are ${isAdult(21) ? 'an adult' : 'a minor'}.`;
console.log(message); // "You are an adult."
Copied!

But don’t overuse putting very long expressions either. For readability, if it’s not short, extract it as an independent variable.

String Concatenation

One of the most frequent uses of Template Literals is simply using them to concatenate text (in fact, everything they do could be done by concatenating text).

Before the introduction of Template Literals, we had to use string concatenation (for example with +), to include variables within texts.

const name = 'Pedro';
const age = 28;
const message = 'Hello, my name is ' + name + ' and I am ' + age + ' years old.';

console.log(message); // "Hello, my name is Pedro and I am 28 years old."
Copied!

With Template Literals it would look like this,

const name = 'Pedro';
const age = 28;
const message = `Hello, my name is ${name} and I am ${age} years old.`;

console.log(message); // "Hello, my name is Pedro and I am 28 years old."
Copied!

Multiline Strings

Template Literals allow defining text strings that span multiple lines, without the need for special escape characters.

const multilineMessage = `
  <div>
    <h1>Header</h1>
    <p>This is a paragraph in a multi-line string.</p>
  </div>
`;
Copied!

This is especially useful for creating long or structured texts (like HTML or long messages).