Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of the backtick character (`) in JavaScript

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

like image 821
vancewang Avatar asked Dec 28 '14 15:12

vancewang


People also ask

What are backticks called in JavaScript?

Backticks aka “template literals” aka “template strings” aka “fancy strings” were introduced in the ES2015 specifications. MDN states “ Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

What is backtick character?

Alternatively known as acute, backtick, left quote, or an open quote, the back quote or backquote is a punctuation mark (`). It's on the same U.S. computer keyboard key as the tilde.

What is a template string in JavaScript?

Template strings are a powerful feature of modern JavaScript released in ES6. It lets us insert/interpolate variables and expressions into strings without needing to concatenate like in older versions of JavaScript. It allows us to create strings that are complex and contain dynamic elements.

What is string interpolation JavaScript?

String interpolation is replacing placeholders with values in a string literal. The string interpolation in JavaScript is performed by template literals (strings wrapped in backticks ` ) and ${expression} as a placeholder.


1 Answers

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.

  • Examples: http://tc39wiki.calculist.org/es6/template-strings/
  • Official specification: ECMAScript 2015 Language Specification, 12.2.9 Template Literal Lexical Components (a bit dry)

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)}`); 
like image 198
13 revs, 9 users 55% Avatar answered Sep 19 '22 17:09

13 revs, 9 users 55%