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".
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.
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.
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.
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.
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)}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With