Chapter 5. Modular Patterns and Practices
In this chapter, we’ll take a look at some of the latest language features and how to leverage those in our programs while reducing complexity in the process. We’ll also analyze concrete coding patterns and conventions that can help us develop simple alternatives to otherwise complex problems.
5.1 Leveraging Modern JavaScript
When used judiciously, the latest JavaScript features can be of great help in reducing the amount of code whose sole purpose is to work around language limitations. This increases signal—the amount of valuable information that can be extracted from reading a piece of code—while eliminating boilerplate and repetition.
5.1.1 Template Literals
Before ES6, the JavaScript community came up with half a dozen ways of arriving at multiline strings: from strings chained with \ escape characters or + arithmetic operators, to using Array#join, or resorting to the string representation of comments in a function—all merely for multiline support.
Further, inserting variables into a string isn’t possible, but that’s easily circumvented by concatenating them with one or more strings:
'Hello '+name+', I\'m Nicolás!'
Template literals arrived in ES6 and resolve multiline strings in a feature that was native to the language, without the need for any clever hacks in user-space.
Unlike strings, with template literals, we can interpolate expressions by using a streamlined syntax. They involve less escaping, too, thanks to using ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access