3
You can actually use any expression inside the curly braces. We will cover expressions in
.
interpolation). String templates provide a shorthand way of injecting values into a
string. String templates use backticks instead of single or double quotes. Here is the
previous example rewritten using string templates:
let
currentTemp
=
19.5
;
const
message
=
`The current temperature is
${
currentTemp
}
\u00b0C`
;
Inside a string template, the dollar sign becomes a special character (you can escape it
with a backslash): if it’s followed by a value
wrapped in curly braces, that value is
inserted into the string.
Template strings are one of my favorite features of ES6, and you’ll see them used
throughout this book.
Multiline Strings
Before ES6, multiline string support was spotty at best. The language specification
allows for escaping the newline at the end of a line of source code, but it’s a feature
I’ve never used due to unreliable browser support. With ES6, the feature is more
likely to be available, but there are some quirks that you should be aware of. Note that
these techniques probably won’t work in a JavaScript console (like the one in your
browser) so you’ll have to actually write a JavaScript file to try these out. For single-
and double-quoted strings, you can escape the newline thusly:
const
multiline
=
"line1\
line2"
;
If you expect
multiline
to be a string with a newline in it, you’ll be surprised: the
slash at the end of the line escapes the newline, but does not insert a newline into the
string. So the result will be
"line1line2"
. If you want an actual newline, you’ll have
to do this:
const
multiline
=
"line1\n\
line2"
;
Backtick strings behave a little more like you might expect:
const
multiline
=
`line1
line2`
;
This will result in a string with a newline. With both techniques, however, any inden‐
tation at the beginning of the line will be included in the resulting string. For exam‐
ple, the following will result in a string with newlines and whitespace before
line2
and
line3
, which may not be desirable:
Special Characters | 43