How to Use ES6 Template Literals in JavaScript

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

ECMAScript 6 – 10 Awesome New Features

ECMAScript 6 – 10 Awesome New Features

Did we know that JavaScript (along with JScript and ActionScript) is an doing of a ubiquitous purpose client-side…Read more

Template literals were introduced in ECMAScript 6. They work utterly likewise to fibre literals; they furnish template values and raw template values, both of that are strings.

However, distinct fibre literals, template literals can furnish values that are multi-lined strings, something we can grasp in a fibre verbatim usually by adding new line characters (n) to it.

Template literals can also create strings with other values (derived from expressions) for that we would have to use a plus operator in a fibre verbatim ("your id is:" + idNo; where idNo is a non-static countenance with a numeric value).

All these facilities make template literals some-more preferable to create fibre values.

Syntax of template literals

The delimiter of a template verbatim is a backtick ` character (also know as backquote impression or grave accent symbol). An countenance inside a verbatim (the value of that is evaluated during runtime and enclosed in a final value constructed by a literal) is enclosed in curly braces {} with a preceding dollar pointer $.

`string ${someExpression} some-more string`

Here are some examples of template literals producing unchanged, substituted (expressions transposed 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 tender template values

In a template literal, a ` (backtick), (backslash), and $ (dollar sign) characters should be escaped regulating a escape impression if they are to be enclosed in their template value.

By default, all shun sequences in a template verbatim are ignored. If we wish to embody it in a output, we need to use a raw template value.

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

var name = "Joan";

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

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

The String.raw process outputs tender template values (the tender fibre form of a template literal). In a above code, a duty call of a raw process is referred to as “tagged template”.

Tagged templates

A tagged template is a function call where, in place of a common parentheses (with discretionary parameters) besides a duty name, there’s a template literal from that a duty gets a arguments.

So, instead of job a duty like this:


It is called like this:


The duty foo is called a tag function. Its initial evidence perceived from a template verbatim is an array called a template object.

The template intent (an array) binds all a fibre values interpreted from a template verbatim and has a raw skill (another array) that binds all a tender (un-escaped) fibre values interpreted from a same literal.

Following a template object, a arguments of a tab duty embody all a evaluated outmost values benefaction in that verbatim (the ones enclosed in a curly braces ${}).

In a formula below, a foo duty is combined to output a arguments. The duty is afterwards called in a tagged template fashion, with a template verbatim carrying dual 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 initial evidence outputted is a template object carrying all a strings interpreted from a template literal, a second and third arguments are a evaluated values of a expressions, name and id.

The raw property

As mentioned before, a template intent has a property called raw that is an array containing all a tender (un-escaped) fibre values interpreted from a template literal. This is how we can entrance a raw property:

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

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

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

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

  // Joan
Use cases of tagged templates

Tagged templates are useful when we need to break a string into apart tools like it’s mostly a box 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 vital browsers.

Below, we can find some examples of tab functions with different signatures that paint a arguments:

var name = "John";

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

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

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

  // Array [ "John" ]

In a bar function, a initial parameter (strVals) is a template object and a second one (that uses a spread syntax) is an array that collected all a evaluated countenance values from a template verbatim upheld to a function.

Put a fibre together

If we wish to obtain a whole sentence (derived from a literal) inside a tab function, concatenate all values of a arrays carrying a template strings and a evaluated countenance values. Like this:

function foo(strs, ...exprs) {

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

  // if there are no expressions enclosed in a literal

name = 'John';

foo`Hello ${name}.`;

The strs array binds all a strings found in a verbatim and exprs binds all a evaluated countenance values from a literal.

If even one countenance value exists concatenate any array value of strs (except a final one) with a same-index value of exprs. Then, during a end, supplement a final value of a strs array to a concatenated string, forming a finish sentence this way.

4 Useful JavaScript Statements You Should Know

4 Useful JavaScript Statements You Should Know

JavaScript statements give us a energy to exercise opposite forms of proof in the code. JavaScript provides us…Read more

Add Comment