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
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:
\u
, for example \u00A9
\u{}
, for example \u{2F804}
\x
, for example \xA9
\
and (a) digit(s), for example \251
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>
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