The grave accent delimits a new type of literal string in Javascript, called string template (or literal template). Introduced in Ecmascript 2015 specification (ES6).
Among the possibilities of a string template, may be mentioned:
Literal line breaking
Unlike "normal" string literals (delimited by single quotes '
or double quotes "
), strings template can house multiple lines without any kind of exhaust:
const name = 'Foo';
const age = 'Bar';
const htmlStr =
`<div>Name: ${name}</div>
<div>Idade: ${age}</div>`;
Interpolation of values
It is possible to interpolate values within a string template. This is useful because it avoids the use of the concatenation operator +
, that often ends up "polluting" the code:
const name = 'Foo';
const age = 'Bar';
const oldWay = 'Olá, chamo-me ' + name + ' e tenho ' + age + ' anos.';
const newWay = `Olá, chamo-me ${name} e tenho ${age} anos.`;
By interpolating some value, it will always be converted to type string
. For that reason, ToString
shall be applied to the interpolated value.
Tagged template string
In a way, you can use a string template as the "argument" of a function. In this case, the function is called tag
and precedes the first acute accent character:
tag`Caracteres da string...`;
Once that expression is evaluated, tag
(which is a function) is invoked. At the first argument is passed the array of each string (separated at the interpolation location). The other arguments (is a variadic function) are the interpolated values themselves. The possibilities of this are infinite. It is the basis for libraries like styled-components
. Another application is to filter the value to be interpolated to, for example, prevent XSS. This article (in English) exemplifies.
String.raw
The String.raw
allows the use of strings without applying escape sequences, such as \n
, \t
etc. The String.raw
is a function tag built-in in the language, so that the tag Function is raw
, method within the global object String
.
This question gives more details on the String.raw
. To documentation may also be useful.
It’s really a "template"?
Despite the name "strings template", this kind of literal string is not exactly a template itself, since, unlike this one, the strings template do not allow further evaluation. Thus, all values that will be interpolated should be in scope at the time when the literal is evaluated by Runtime. This theme is most discussed in this other answer.