ES-2015 multiline and template strings

The previous example showed two of the new features introduced with ES-2015, multiline and template strings. The feature is meant to simplify our life while creating text strings.

The existing string representations use single quotes and double quotes. Template strings are delimited with the backtick character that's also known as the grave accent (or, in French, accent grave):

`template string text`

Before ES-2015, one way to implement a multiline string was this construct:

["<html><head><title>Hello, world!</title></head>",
 "<body><h1>Hello, world!</h1>",
 "<p><a href='/osinfo'>OS Info</a></p>",
 "</body></html>"]
.join('
')

Yes, this is the code used in the same example in previous versions of this book. This is what we can do with ES-2015:

`<html><head><title>Hello, world!</title></head>
<body><h1>Hello, world!</h1>
<p><a href='/osinfo'>OS Info</a></p>
</body></html>`

This is more succinct and straightforward. The opening quote is on the first line, the closing quote on the last line, and everything in between is part of our string.

The real purpose of the template strings feature is supporting strings where we can easily substitute values directly into the string. Most other programming languages support this ability, and now JavaScript does too.

Pre-ES-2015, a programmer would do this:

[ …
  "<tr><th>OS Type</th><td>{ostype} {osplat} {osarch} {osrelease}</td></tr>"
  … ].join('
')
.replace("{ostype}", os.type())
.replace("{osplat}", os.platform())
.replace("{osarch}", os.arch())
.replace("{osrelease}", os.release())

Again, this is extracted from the same example in previous versions of this book. With template strings, this can be written as follows:

`...<tr><th>OS Type</th><td>${os.type()} ${os.platform()} ${os.arch()} ${os.release()}</td></tr>...`

Within a template string, the part within the ${ .. } brackets is interpreted as an expression. It can be a simple mathematical expression, a variable reference, or, as in this case, a function call.

The last thing to mention is a matter of indentation. In normal coding, one indents a long argument list to the same level as the containing function call. But, for these multiline string examples, the text content is flush with column 0. What's up?

This may impede readability of your code, so it's worth weighing code readability against another issue, excess characters in the HTML output. The blanks we would use to indent the code for readability will become part of the string and will be output in the HTML. By making the code flush with column 0, we don't add excess blanks to the output at the cost of some code readability.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset