Usage of the backtick character (`) in JavaScript
Asked Answered
G

12

447

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".

Goldfish answered 28/12, 2014 at 15:59 Comment(4)
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. https://mcmap.net/q/80422/-usage-of-the-backtick-character-in-javascriptMagnetite
“backgrave” is ridiculous, because there is no forward grave accent – that's called an acute accentFeatherstone
@WalterTross: I agree. The correct name for this character is 'grave' or 'grave accent'. One of many frequently misnamed.Sow
From Backtick: "The backtick ` is a typographical mark used mainly in computing. It is also known as backquote, grave, or grave accent."Verulamium
C
459

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)}`);
Conformance answered 28/12, 2014 at 15:59 Comment(7)
Are there any viable polyfils for this given the lack of support for it?Matthus
@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 ES5Conformance
Tagged template literals using backticks! This is valid and works well: alert`1`.Multiphase
@UnionP Supported by all major browsers including MS Edge: kangax.github.io/compat-table/es6/#test-template_literalsThroaty
Guys, I am trying to use template literals (``) in my Google Apps script IDE and it says "Illegal character". What's wrong?Ambassadoratlarge
@Ambassadoratlarge 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.Conformance
I feel like backticks are good for inserting quotes within quotes without having to worry about the inner quotes clashing with the outer ones. For example, alert(They said, "Hello World!");Sceptre
H
276

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"
Hughett answered 15/10, 2016 at 18:9 Comment(6)
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).Sim
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.Pentagram
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...).Guadiana
The sentence that includes "is an interpolated string literal is just lexically scoped" is incomprehensible. Can you fix it?Verulamium
@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.Deification
use of rajnikant wants an upvoteWaddell
M
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?
Mouton answered 11/11, 2016 at 8:56 Comment(0)
N
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.

Nocturn answered 7/8, 2019 at 6:4 Comment(0)
H
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
Hm answered 8/9, 2017 at 20:34 Comment(0)
J
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.

Jittery answered 2/10, 2018 at 16:49 Comment(0)
W
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>
Werth answered 22/1, 2019 at 0:49 Comment(1)
did nobody else chuckle cmon nowJevons
S
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.

Snakebite answered 11/2, 2023 at 19:39 Comment(2)
How does this add to the already provided answers?Archaimbaud
I meant to mention Usage of the backtick character (`) in JavaScriptSnakebite
P
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};
Pudendum answered 14/12, 2020 at 23:13 Comment(0)
A
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.
Arapaho answered 16/10, 2020 at 0:50 Comment(0)
F
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}\``) );
}
Foreignborn answered 3/11, 2020 at 9:52 Comment(0)
M
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}.`;
Matey answered 12/4 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.