Modern JavaScript Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

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 were earlier known as template strings, but current JS specifications don't use that expression any more. For more information, go to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals.

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}`;
We'll fight the temptation to include logic in templates later, when we work in React (from Chapter 6, Developing with React, to Chapter 10, Testing your Application) and see how we can render components.