How to Use ES6 Template Literals in JavaScript

In programming, the term “literal” refers to the notation of values in code. For instance, we notate a string value with a string literal that are characters enclosed in double or single quotes ("foo", 'bar', "This is a string!").

ECMAScript 6 – 10 Awesome New Features

ECMAScript 6 – 10 Awesome New Features

Did you know that JavaScript (along with JScript and ActionScript) is an implementation of a general purpose client-side…Read more

Template literals were introduced in ECMAScript 6. They work quite similarly to string literals; they produce template values and raw template values, both of which are strings.

However, unlike string literals, template literals can produce values that are multi-lined strings, something you can achieve in a string literal only by adding new line characters (\n) to it.

Template literals can also create strings with other values (derived from expressions) for which you would have to use the plus operator in a string literal ("your id is:" + idNo; where idNo is a variable expression with a numeric value).

All these features make template literals more preferable to create string values.

Syntax of template literals

The delimiter of a template literal is the backtick ` character (also know as backquote character or grave accent symbol). An expression inside the literal (the value of which is evaluated during runtime and included in the final value produced by the literal) is enclosed in curly braces {} with a preceding dollar sign $.

`string ${someExpression} more string`

Here are some examples of template literals producing unchanged, substituted (expressions replaced with their evaluated values), and multi-lined strings.

// hello

var name = "Joan";
console.log(`hello ${name}`);
// hello Joan

console.log(`Dear Joan,
// Dear Joan,
// Welcome.

Escaping & raw template values

In a template literal, the ` (backtick), \ (backslash), and $ (dollar sign) characters should be escaped using the escape character \ if they are to be included in their template value.

By default, all escape sequences in a template literal are ignored. If you want to include it in the output, you need to use its raw template value.

console.log(`inline code in markup: \`code\``);
// inline code in markup: `code`

var name = "Joan";

console.log(`hello \${name}.`);
// hello ${name}.

console.log(String.raw`hello \${name}.`);
// hello \${name}.

The String.raw method outputs raw template values (the raw string form of a template literal). In the above code, the function call of the raw method is referred to as “tagged template”.

Tagged templates

A tagged template is a function call where, in place of the usual parentheses (with optional parameters) besides the function name, there’s a template literal from which the function gets its arguments.

So, instead of calling a function like this:


It is called like this:


The function foo is called a tag function. Its first argument received from the template literal is an array called the template object.

The template object (an array) holds all the string values interpreted from the template literal and has a raw property (another array) that holds all the raw (un-escaped) string values interpreted from the same literal.

Following the template object, the arguments of the tag function include all the evaluated external values present in that literal (the ones enclosed in the curly braces ${}).

In the code below, the foo function is created to output its arguments. The function is then called in the tagged template fashion, with a template literal carrying two expressions (name and id).

var name = "John";
var id = 478;

foo`hello ${name}. your id is: ${id}.`;

function foo(){
  // Array [ "hello ", ". your id is: ", "." ]

  // John

  // 478

The first argument outputted is the template object carrying all the strings interpreted from the template literal, the second and third arguments are the evaluated values of the expressions, name and id.

The raw property

As mentioned before, the template object has a property called raw which is an array containing all the raw (un-escaped) string values interpreted from the template literal. This is how you can access the raw property:

var name1 = "John",
name2 = "Joan";

foo`hello \${name1}, ${name2}, how are you both?`;

function foo(){
  // Array ["hello ${name1}, ",", how are you both?"]

  // Array ["hello \${name1}, ",", how are you both?"]

  // Joan
Use cases of tagged templates

Tagged templates are useful when you need to break a string into separate parts like it’s often the case in a URL, or while parsing a language. You’ll find a collection of tagged template examples here.

Other than IE, template literals are supported in all major browsers.

Below, you can find some examples of tag functions with different signatures that represent the arguments:

var name = "John";

foo`hello ${name}, how are you both?`;
bar`hello ${name}, how are you both?`;

function foo(...args){
  // Array [ Array ["hello ",", how are you both?"], "John"]

function bar(strVals, ...exprVals){
  // Array [ "hello ", ", how are you both?" ]

  // Array [ "John" ]

In the bar function, the first parameter (strVals) is the template object and the second one (that uses the spread syntax) is an array that gathered all the evaluated expression values from the template literal passed to the function.

Put the string together

If you want to obtain the whole sentence (derived from the literal) inside the tag function, concatenate all values of the arrays carrying the template strings and the evaluated expression values. Like this:

function foo(strs, ...exprs) {

  // if there are any expressions included in the literal
  if (exprs.length !== 0) {
      var n = strs.length - 1,
      		result = '';
      for (var i = 0; i < n; i++) {
          result += strs[i] + exprs[i];
      result += strs[n];
      //"Hello John."

  // if there are no expressions included in the literal

name = 'John';

foo`Hello ${name}.`;

The strs array holds all the strings found in the literal and exprs holds all the evaluated expression values from the literal.

If even one expression value exists concatenate each array value of strs (except the last one) with the same-index value of exprs. Then, at the end, add the last value of the strs array to the concatenated string, forming a complete sentence this way.

4 Useful JavaScript Statements You Should Know

4 Useful JavaScript Statements You Should Know

JavaScript statements give us the power to implement different types of logic in our code. JavaScript provides us…Read more