451

In JavaScript, a backtick seems to work the same as a single quote. For instance, I can use a backtick to define a string like this:

var s = `abc`;

Is there a way in which the behavior of the backtick actually differs from that of a single quote?


† Note that among programmers, "backtick" is one name for what is more generally called the grave accent. Programmers also sometimes use the alternate names "backquote" and "backgrave". Also, on Stack Overflow and elsewhere, other common spellings for "backtick" are "back-tick" and "back tick".

4
  • 2
    Please read below for the usage of Tagged Templates as well. This is a different use than the question being asked. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… And this is explained in one of the longer answers below. stackoverflow.com/a/40062505/3281336
    – PatS
    Commented Aug 6, 2019 at 15:00
  • 26
    “backgrave” is ridiculous, because there is no forward grave accent – that's called an acute accent Commented Feb 18, 2020 at 16:48
  • 2
    @WalterTross: I agree. The correct name for this character is 'grave' or 'grave accent'. One of many frequently misnamed.
    – david.pfx
    Commented Sep 4, 2022 at 7:06
  • 6
    From Backtick: "The backtick ` is a typographical mark used mainly in computing. It is also known as backquote, grave, or grave accent." Commented Oct 18, 2022 at 19:16

12 Answers 12

462

This is a feature called template literals.

They were called "template strings" in prior editions of the ECMAScript 2015 specification.

Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.

Template literals can be used to represent multi-line strings and may use "interpolation" to insert variables:

var a = 123, str = `---
   a is: ${a}
---`;
console.log(str);

Output:

---
   a is: 123
---

What is more important, they can contain not just a variable name, but any JavaScript expression:

var a = 3, b = 3.1415;

console.log(`PI is nearly ${Math.max(a, b)}`);
7
  • 2
    Are there any viable polyfils for this given the lack of support for it? Commented Jul 7, 2016 at 18:16
  • 4
    @AlexanderDixon, no you can't polyfill this language feature in the classical sense, though you might use templates from Underscore or lodash for variables in strings in combination with multilining strings using arrays: ["a", "b"].join(""); // both string elements written in new lines. But apart from this one might use a "transpiler" like Babel to convert ES6+ to ES5 Commented Jul 7, 2016 at 19:29
  • 4
    Tagged template literals using backticks! This is valid and works well: alert`1`. Commented Jul 29, 2016 at 20:59
  • @UnionP Supported by all major browsers including MS Edge: kangax.github.io/compat-table/es6/#test-template_literals Commented Aug 6, 2018 at 22:59
  • 3
    @kiki it looks like the script language is a variant of ECMAScript. Google App scripts do not support ECMAScript 2015 features obviously. I was unable to find an official specification what language they're using. Commented Mar 30, 2019 at 11:53
277
+50

ECMAScript 6 comes up with a new type of string literal, using the backtick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.

let person = {name: 'RajiniKanth', age: 68, greeting: 'Thalaivaaaa!' };

let usualHtmlStr = "<p>My name is " + person.name + ",</p>\n" +
  "<p>I am " + person.age + " old</p>\n" +
  "<strong>\"" + person.greeting + "\" is what I usually say</strong>";

let newHtmlStr =
 `<p>My name is ${person.name},</p>
  <p>I am ${person.age} old</p>
  <p>"${person.greeting}" is what I usually say</strong>`;

console.log(usualHtmlStr);
console.log(newHtmlStr);

As you can see, we used the ` around a series of characters, which are interpreted as a string literal, but any expressions of the form ${..} are parsed and evaluated inline immediately.

One really nice benefit of interpolated string literals is they are allowed to split across multiple lines:

var Actor = {"name": "RajiniKanth"};

var text =
`Now is the time for all good men like ${Actor.name}
to come to the aid of their
country!`;
console.log(text);
// Now is the time for all good men like RajiniKanth
// to come to the aid of their
// country!

Interpolated Expressions

Any valid expression is allowed to appear inside ${..} in an interpolated string literal, including function calls, inline function expression calls, and even other interpolated string literals!

function upper(s) {
  return s.toUpperCase();
}
var who = "reader"
var text =
`A very ${upper("warm")} welcome
to all of you ${upper(`${who}s`)}!`;
console.log(text);
// A very WARM welcome
// to all of you READERS!

Here, the inner `${who}s` interpolated string literal was a little bit nicer convenience for us when combining the who variables with the "s" string, as opposed to who + "s". Also note that an interpolated string literal is just lexically scoped where it appears, not dynamically scoped in any way:

(e.g. below: a name variable gets interpolated with the value held in the scope where the template-literal is defined; assigning another value in the foo function's scope will have no effect)

function foo(str) {
  var name = "foo";
  console.log(str);
}
function bar() {
  var name = "bar";
  foo(`Hello from ${name}!`);
}
var name = "global";
bar(); // "Hello from bar!"

Using the template literal for the HTML is definitely more readable by reducing the annoyance.

The plain old way:

'<div class="' + className + '">' +
  '<p>' + content + '</p>' +
  '<a href="' + link + '">Let\'s go</a>'
'</div>';

With ECMAScript 6:

`<div class="${className}">
  <p>${content}</p>
  <a href="${link}">Let's go</a>
</div>`
  • Your string can span multiple lines.
  • You don't have to escape quotation characters.
  • You can avoid groupings like: '">'
  • You don't have to use the plus operator.

Tagged Template Literals

We can also tag a template string, when a template string is tagged, the literals and substitutions are passed to function which returns the resulting value.

function myTaggedLiteral(strings) {
  console.log(strings);
}

myTaggedLiteral`test`; //["test"]

function myTaggedLiteral(strings, value, value2) {
  console.log(strings, value, value2);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5

We can use the spread operator here to pass multiple values. The first argument—we called it strings—is an array of all the plain strings (the stuff between any interpolated expressions).

We then gather up all subsequent arguments into an array called values using the ... gather/rest operator, though you could of course have left them as individual named parameters following the strings parameter like we did above (value1, value2, etc.).

function myTaggedLiteral(strings, ...values) {
  console.log(strings);
  console.log(values);
}

let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5

The argument(s) gathered into our values array are the results of the already evaluated interpolation expressions found in the string literal. A tagged string literal is like a processing step after the interpolations are evaluated, but before the final string value is compiled, allowing you more control over generating the string from the literal. Let's look at an example of creating reusable templates.

const Actor = {
  name: "RajiniKanth",
  store: "Landmark"
}

const ActorTemplate = templater`<article>
  <h3>${'name'} is a Actor</h3>
  <p>You can find his movies at ${'store'}.</p>

</article>`;

function templater(strings, ...keys) {
  return function(data) {
    let temp = strings.slice();
    keys.forEach((key, i) => {
      temp[i] = temp[i] + data[key];
    });
    return temp.join('');
  }
};

const myTemplate = ActorTemplate(Actor);
console.log(myTemplate);

Raw Strings

Our tag functions receive a first argument we called strings, which is an array. But there’s an additional bit of data included: the raw unprocessed versions of all the strings. You can access those raw string values using the .raw property, like this:

function showraw(strings, ...values) {
  console.log(strings);
  console.log(strings.raw);
}
showraw`Hello\nWorld`;

As you can see, the raw version of the string preserves the escaped \n sequence, while the processed version of the string treats it like an unescaped real new-line. ECMAScript 6 comes with a built-in function that can be used as a string literal tag: String.raw(..). It simply passes through the raw versions of the strings:

console.log(`Hello\nWorld`);
/* "Hello
World" */

console.log(String.raw`Hello\nWorld`);
// "Hello\nWorld"
6
  • 3
    Great answer! Minor comment, in your Tagged Template Literals section, I believe the two example array outputs for myTaggedLiteral`test ${someText} ${2 + 3}`; should be //["test ", " "] (i.e. not trimmed strings). Commented Feb 11, 2017 at 12:11
  • 2
    Good explanation and wide coverage, thank you. Just wanted to add that there is also a good overview on the Mozilla developer site Template literals (Template strings) which covers some extra aspects.
    – Dev Ops
    Commented Apr 10, 2019 at 7:35
  • 2
    Nit: "ECMAScript 6 comes up with a new type of string literal" It's not a string literal, it's a template literal. It results in a string when evaluated if it's untagged. This isn't just dogmatic, there are places you can use string literals where template literals are not allowed (such as uncomputed parameter names, module identifiers...). Commented Aug 6, 2019 at 14:50
  • 1
    The sentence that includes "is an interpolated string literal is just lexically scoped" is incomprehensible. Can you fix it? Commented Feb 28, 2020 at 23:15
  • @PeterMortensen it's not easily comprehensible but that's the terminology to use. – However, I've added a note above the example code; hopefully the scope behavior is clearer now. Commented Nov 29, 2022 at 16:18
33

Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.

Features:

  • we can interpolate any kind of expression in the template literals.
  • They can be multi-line.

Note: we can easily use single quotes (') and double quotes (") inside the backticks (`).

Example:

var nameStr = `I'm "Alpha" Beta`;

To interpolate the variables or expression we can use the ${expression} notation for that.

var name = 'Alpha Beta';
var text = `My name is ${name}`;
console.log(text); // My name is Alpha Beta

Multi-line strings means that you no longer have to use \n for new lines anymore.

Example:

const name = 'Alpha';
console.log(`Hello ${name}!
How are you?`);

Output:

Hello Alpha!
How are you?
21

Apart from string interpolation, you can also call a function using back-tick.


var sayHello = function () {
    console.log('Hello', arguments);
}

// To call this function using ``

sayHello`some args`; // Check console for the output

// Or
sayHello`
    some args
`;

Check styled component. They use it heavily.

17

Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.

Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}. The placeholder / expressions get passed to a function. The default function just concatenates the string.

To escape a backtick, put a backslash before it:

`\`` === '`'; => true

Use backticks to more easily write multi-line string:

console.log(`string text line 1
string text line 2`);

or

console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);

vs. vanilla JavaScript:

console.log('string text line 1\n' +
'string text line 2');

or

console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');

Escape sequences:

  • Unicode escapes started by \u, for example \u00A9
  • Unicode code point escapes indicated by \u{}, for example \u{2F804}
  • Hexadecimal escapes started by \x, for example \xA9
  • Octal literal escapes started by \ and (a) digit(s), for example \251
16

Summary:

Backticks in JavaScript is a feature which is introduced in ECMAScript 6 // ECMAScript 2015 for making easy dynamic strings. This ECMAScript 6 feature is also named template string literal. It offers the following advantages when compared to normal strings:

  • In Template strings linebreaks are allowed and thus can be multiline. Normal string literals (declared with '' or "") are not allowed to have linebreaks.
  • We can easily interpolate variable values to the string with the ${myVariable} syntax.

Example:

const name = 'Willem';
const age = 26;

const story = `
  My name is: ${name}
  And I'm: ${age} years old
`;

console.log(story);

Browser compatibility:

Template string literal are natively supported by all major browser vendors (except Internet Explorer). So it is pretty safe to use in your production code. A more detailed list of the browser compatibilities can be found here.

8

The good part is we can make basic maths directly:

let nuts = 7

more.innerHTML = `

<h2>You collected ${nuts} nuts so far!

<hr>

Double it, get ${nuts + nuts} nuts!!

`
<div id="more"></div>

It became really useful in a factory function:

function nuts(it){
  return `
    You have ${it} nuts! <br>
    Cosinus of your nuts: ${Math.cos(it)} <br>
    Triple nuts: ${3 * it} <br>
    Your nuts encoded in BASE64:<br> ${btoa(it)}
  `
}

nut.oninput = (function(){
  out.innerHTML = nuts(nut.value)
})
<h3>NUTS CALCULATOR
<input type="number" id="nut">

<div id="out"></div>

1
  • 5
    did nobody else chuckle cmon now
    – StayCool
    Commented Jun 3, 2019 at 13:06
4

The backtick character (`) in JavaScript is used to define template literals. A template literal is a special type of string that allows you to embed expressions, which are evaluated and included in the final string. They are denoted by being surrounded by the backtick (`) character instead of single quotes (') or double quotes (").

Here's an example of using a template literal to embed an expression in a string:

const name = "Akila";
const message = `Hello, ${name}!`;
console.log(message); // Output: Hello, Akila!

In the example above, the expression ${name} is evaluated and included in the final string, which is assigned to the message variable.

Template literals also provide several convenient features, such as multi-line strings and string interpolation. Multi-line strings allow you to include line breaks in your strings, which is especially useful for creating formatted text.

Here's an example of using a multi-line string with a template literal:

const message = `This is a
multi-line string.`;
console.log(message);

output

This is a
multi-line string.

In conclusion, the backtick character (`) in JavaScript is used to define template literals, which are a convenient way to include expressions and multi-line strings in your JavaScript code.

2
  • How does this add to the already provided answers? Commented Feb 15, 2023 at 17:32
  • I meant to mention Usage of the backtick character (`) in JavaScript Commented Feb 16, 2023 at 19:36
1

A lot of the comments answer most of your questions, but I mainly wanted to contribute to this question:

Is there a way in which the behavior of the backtick actually differs from that of a single quote?

A difference I've noticed for template strings is the disability to set one as an object property. More information in this post; an interesting quote from the accepted answer:

Template strings are expressions, not literals1.

But basically, if you ever wanted to use it as an object property you'd have to use it wrapped with square brackets.

// Throws error
const object = {`templateString`: true};

// Works
const object = {[`templateString`]: true};
0

It's a pretty useful functionality, for example here is a Node.js code snippet to test the set up of a 3 second timing function.

const waitTime = 3000;
console.log(`setting a ${waitTime/1000} second delay`);

Explanation

  1. Declare wait time as 3000
  2. Using the backtick you can embed the result of the calculation of 'wait time' divided by 1000 in the same line with your chosen text.
  3. Further calling a timer function using the 'waitTime' constant will result in a 3 second delay, as calculated in the console.log argument.
0

You can make a template of templates too, and reach private variable.

var a= {e:10, gy:'sfdsad'}; //global object

console.log(`e is ${a.e} and gy is ${a.gy}`); 
//e is 10 and gy is sfdsad

var b = "e is ${a.e} and gy is ${a.gy}" // template string
console.log( `${b}` );
//e is ${a.e} and gy is ${a.gy}

console.log( eval(`\`${b}\``) ); // convert template string to template
//e is 10 and gy is sfdsad

backtick( b );   // use fonction's variable
//e is 20 and gy is fghj

function backtick( temp ) {
  var a= {e:20, gy:'fghj'}; // local object
  console.log( eval(`\`${temp}\``) );
}
0
  1. Creating Template Literals: Template literals allow for embedded expressions and multiline strings.

const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!

  1. Embedded Expressions: You can embed expressions inside ${} within a template literal.

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

  1. Multiline Strings: Template literals can span multiple lines without needing to use special characters like \n.

const multiline = `
This is a
multiline
string.
`;
console.log(multiline);

  1. Tagged Templates: Template literals can be tagged with a function that can preprocess the template string.

function myTag(strings, ...values) {
    console.log(strings); // Array of string literals
    console.log(values);  // Array of interpolated values
}

const value1 = 10;
const value2 = 20;
myTag`The values are ${value1} and ${value2}.`;

Not the answer you're looking for? Browse other questions tagged or ask your own question.