Interpolating in template strings
Everybody has, at one time or another, used common operators to build up a string, as in the following code fragment:
let name = lastName + "," + firstName;
let clientUrl = basicUrl + "/clients/" + clientId + "/";
JS has now added template literals, providing an easy way to include variable text and produce multiple line strings. String interpolation is quite simple, and the preceding code could be rewritten as follows:
let name = `${lastName}, ${firstName}`;
let clientUrl = `${basicUrl}/clients/${clientId}/`;
Template literals are delimited by back-tick characters (`...`). You use ${...} wherever you want some value or expression to be substituted:
let confirm = `Special handling: ${flagHandle ? "YES" : "NO"}`;
Of course, it's easy to go overboard and start pushing too much logic when interpolating. I would recommend avoiding code such as the following for just that reason:
let list = ["London", "Paris", "Amsterdam", "Berlin", "Prague"];
let sched = `Visiting ${list.length > 0 ? list.join(", ") : "no cities"}`;
// Visiting London, Paris, Amsterdam, Berlin, Prague
If list had been empty, "Visiting no cities" would have been produced instead. It's far clearer if you push logic out of templates; even if the resulting code is somewhat larger, it will gain in clarity:
let list = ["London", "Paris", "Amsterdam", "Berlin", "Prague"];
let destinations = list.length > 0 ? list.join(", ") : "no cities";
let sched = `Visiting ${destinations}`;