Javascript: How Backticks Work (“)

Javascript: How Backticks Work (“)

Discover the main uses of backticks in JavaScript

Image for postPhoto by Nhu Nguyen on Unsplash

As you know, in JavaScript there are two main ways to declare strings:

  • Using single quotes ”.
  • Using double quotes “”.

However, with the ES2015 specification, it was possible to create what is known as template literals or template strings for which it is enough to encapsulate text in backticks:

`some text`

This will give us a number of advantages over the two main methods that I will describe throughout this article. Let?s see them.

Concatenate and Interpolate Strings

This is probably one of the most widespread and popularized uses of backticks since it will allow us to concatenate and interpolate strings so our code is much cleaner.

We are going to look at a few examples comparing the old syntax with the one provided by the backticks.

const name = ‘Gerardo’;const surname = ‘Fernndez’;const telephone = ‘123 123 123’;// “Old syntax”const userInfo = ‘User info: ‘ + name + ‘ ‘ + surname + ‘ ‘ + telephone;// “New syntax”const userInfo = `User info: ${name} ${surname} ${telephone}`;

As you can see, thanks to the template literals, we obtain a code that is much easier to read, saving us the concatenation of multiple strings through the + operator.

Of course, we can also execute code within template strings:

const user = getUserFromApi();// “Old syntax”const userInfo = ‘User info: ‘ + user.getName() + ‘ ‘ + user.getEmail();// “New syntax”const userInfo = `User info: ${user.getName()} ${user.getEmail()}`;

It is Not Necessary to Escape the Characters ? and ? Using

Another advantage of using backticks ( “ ) is that it is no longer necessary to escape double quotes ( “” ) or single quotes ( ” ), something that we are usually forced to when we work with languages such as English:

const foo = ‘Can’t connect to the server’;const bar = `Can’t connect to the server`;

Or for example:

const foo = “Error: “Introduce a valid email””;const bar = `Error: “Introduce a valid email”`;

So, again, we get much more readable code.

Strings in Several Lines

In JavaScript, it?s not possible to declare strings on several lines. For example, if we try the following:

const html = “<article><h2>Article title</h2></article>”;

We get the following error:

SyntaxError: “” string literal contains an unescaped line break

Which is quite awkward, especially when we are creating HTML. The alternative we had until ECMA2015 was to use the new line character (n ):

const html = “<article> <h2>Article title</h2> </article>”;

But that nonetheless brings problems at compile time:

The whitespace at the beginning of each line can?t be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript. ? Stack Overflow

Another option is to use the + operator:

const html = ‘<article>’ +'<h2>Article title</h2>’ +'</article>’;

However, with backticks we can write the following:

const html = `<article><h2>Article title</h2></article>`;

So the code we get is really clean.

Of course, it?s important to remember the spaces aren?t removed, so if we create a string as follows ?

const string = `First line Second line`

? what we?ll get will be the following:

First Second

So we will have to resort to the trim method to avoid extra spaces.

Tagged Templates

Another feature provided by backticks is the possibility of creating what are known as tagged templates (also known as tag functions), something that is used by libraries as popular as Apollo or Styled Components:

// Apollo queryconst query = gql` query { … }// Styled componentsconst Container = styled.div` width: 1000px; background: red;`;

Both styled.div and gql are really functions (tag functions) that extract their arguments from a literal template (that is, wrapping text in backticks).

In the case, for example, of the styled component Container, what we get is a React component that represents a div with the following aspect:

<div style=”width: 1000px; background:red”>…</div>

To understand how these types of functions work, suppose we have the sayHello function declared as follows:

function foo() { console.log(arguments[0]); console.log(arguments[1]); console.log(arguments[2]);}

If we now invoke it as if it were a function tag:

const varOne = ‘bar’;const varTwo = ‘zeta’;foo`This is bar: ${varOne} and zeta: ${varTwo}`;

What we?ll get on the console will be:

[“This is bar: “, ” and zeta: “, “”] (array)bar (string)zeta (string)

That is, the function tag is receiving three arguments:

  • The first is an array in which the literal match appears in several strings using the expressions ${…} as breakpoints
  • The rest of the arguments (arguments[1] and arguments[2]) are the result of the variables already interpolated ( bar y zeta )

Taking advantage of the spread operator, we can rewrite our foo function as follows:

function foo(literals, …expressions) { console.log(literals); console.log(expressions[0]); console.log(expressions[1]);}

In this way, the length of the literals array will always be that of the expressions array plus one.

From this moment on, the possibilities offered by tag functions are very varied, as demonstrated by the Apollo and Styled Components libraries or, for example, the following example where we can see how these types of functions are used to translate texts from our application:

const name = ‘Gerardo’;const email = ‘[email protected]’;console.log(i18n`Hi ${name}, your email is ${email}`);// Hola Gerardo, tu email es [email protected]

Final Thoughts

As you can see, although at first it may be a JavaScript feature that goes unnoticed, tagged-template literals give us a lot of versatility when writing code and have become increasingly popular thanks to libraries such as Apollo and Styled Components.

I hope this article has helped you to have a first approach to them or reinforce concepts such as tag functions.


No Responses

Write a response