Template literals

One tick to string them all

A template is a small back-tick that was anticipated for a long time. It has a huge impact on the way JavaScript can handle strings. This small back-tick is can be seen as the tick that moves JavaScript from the middle ages into a pre-modern language.

Unlike regular string that is marked by a single ( ‘ ) or double ( “ ) quotes, template literals are marked by back-ticks ( ` ).

Multi-line strings

Once upon a time, if you wanted to write a long and complicated block of text, you needed to do something like this:

var someHtml = "<div class=\"main\">" + 
" <p class=\"title\">My first Budahistic song</p>" +
" <h1 onclick=\"showTip('Buddha and the frog')\">" +
" Buddha and the frog" +
" </h1>" +
" <ul>" +
" <li>Once a statue of Buddha </li>" +
" <li>was sitting in the fog </li>" +
" <li>Nearby him, sat a frog </li>" +
" <li> </li>" +
" <li>Since there was nothing to do along </li>" +
" <li>the frog slept all along </li>" +
" <li>and this is the end of the song</li> +
" </ul>" +
"</div>"; 

Did you see the missing quote on the end of the song? The error been done by mistake, but left on purpose. With the template literals, and with a tiny back-ticks, it allows us to use freestyle text with line breaks:

let someHtml = `
<div>
<p class="title">My first Budahistic song</p>
<h1 onclick="showTip('Buddha and the frog')">
Buddha and the frog
</h1>
<ul>
<li>Once a statue of Buddha </li>
<li>was sitting in the fog </li>
<li>Nearby him, sat a frog </li>
<li> </li>
<li>Since there was nothing to do along </li>
<li>the frog slept all along </li>
<li>and this is the end of the song</li>
</ul>
</div>`; 

No need to keep track if we are using the single quote as the string wrapper, or the double quotes. No need for like brakes. No need to slashes quotes and all the other annoying games we needed to create the text. 

Expression interpolation

JavaScript template literals provide the option to add variable within the template. 

// On the old days:
var text = "My name is" + name + " " + lastName + ".";

// With template literals:
let test = `My name is ${name} ${lastName}.';

The expression interpolator can handle all kinds of expression:

let one = 1;

let text1 = `Hi, I know math: ${one+2} == 3`;

let days = ["Mon", "Tue", "Wed", "Thurs", "Fri", "Sat", "Sun"];
let sdaysList = `
<p>
<b>Days</b>:
${days.map(day => `
<span>${day}</span>`).join(", ")}
</p>`;

Using a undefined variable will throw an error:

let text = `Lets display undefined var: ${undefinedVar}`;
//Uncaught ReferenceError: undefinedVar is not defined

Nesting templates

Expression interpolators are set at ‘compilation’ time, so you can nest one template within the other: 

let userName = `${name} ${lastName}`;
let theBond = `My name is ${lastName}, ${userName}`;
theBond == 'My name is Bond, Jams Bond';

Condition interpolators

Yup, you probably got the idea:

let html = `
<div class="my-${isBig?'big':'small'}-div>
size
</div>`;in compile time

Tagged templates

There is the option to create our own template function as a Tagged Literal. This adds two additional options: string manipulations & runtime compilation 

function bond(subStrings,...values){
return `My name is ${values[1]}, ${values[0]} ${values[1]}`;
}
let name='Jams',lastName='Bond';
bond`Hi, I'm ${name}${lastName}` == "My name is Bond, Jams Bond";

Notice the last line, we run the function by using the single-tick sign.

The first argument in the tagged template function is a list of the template sub-strings with a raw list at the end (will be explained later).  The following variables are the list of values. 

function taggedLiteral(subStrings,...values) {
console.log(subStrings);
console.log(values);
}

let someValue = 'bla';
taggedLiteral`first ${someValue} string`;
//["first ", " string", raw: Array(2)["first ", " string"]]
//['bla']

Some more useful’ish examples:

function myStyledP(strings, ...values) {
return `
<p style="
${strings.map((string,i) =>
`${string}:${values[i]};`
)}
${values[values.length-1]}
<p>`;
}

myStyledP`
background${'red'}
color${'blue'}
My P`;

//<p style="background:red;color:blue">My P</p>

If you want a functional example:

function currency(strings, …values){
switch(currentCurrency){
case '$': return `${strings[0]} ${values[0]}$`;
case '€': return `€${values[0]} ${strings[0]}`;
}
}

let currentCurrency = '$';
currency`pay ${5}` == "pay 5$";

currentCurrency = '€';
currency`pay ${5}` == "€5 pay";

Since it’s executed at run time, you can do:

function time(s,...v){
return `Time: ${(new Date).toString().split(' ')[4]}`;
}
//time`` == "Time: 13:19:18";
function button(text){   
this.text = text;
}
button.prototype.toString = function(){
return `The ${this.text} button works`;
}
let a = new button('Magic');
a.toString(); // "The Magic button works"

After all this, I must quote Ben Ilegbodu: “I have yet to have the “aha!” moment as to why JavaScript developers would want to use the feature”.

Raw strings

As mentioned, the last element on the first variable is a list of the sub-strings as raw strings. It’s the original strings without processing escape sequences. You can get the same value by using String.raw:

`let's ${1+2} break \nthe raw ` == "let's 3 break
the raw "
String.raw`let's ${1+2} break \nthe raw ` == "let's 3 break \nthe raw "

Conclusion

The simple use of the single-tick template literal is a code changer. About the other cases, I’m still looking for the exact need.