Writing multiline strings

Another feature of the new template literals is that they can span several lines. With earlier versions of JS, if you wanted to produce multiple lines of text, you had to insert newline characters (" ") in the output string, like so:

let threeLines = "These are
three lines
of text";
console.log(threeLines);
// These are
// three lines
// of text

With template strings, you can just write the line as desired:

let threeLines = `These are
three lines
of text`;

However, I would recommend against this practice. Even if the code may seem more legible, when it gets indented, the result looks ugly, since continuation lines must start at the first column—do you see why? Check out the following code—the continuation lines are pushed to the left, breaking the visual continuity of the indented code:

if (someCondition) {
.
.
.
if (anotherCondition) {
.
.
.
var threeLines = `These are
three lines
of text`;
}
}

You can use a backslash to escape characters that are not meant to be part of templating:

let notEscaped1 = `this is ${not} interpolation\nright? `;
// "this is ${not} interpolation right? "
You might want to look into String.raw (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw) for an alternative to this way of avoiding templating. You can just avoid templating altogether, since an informal poll has shown that practically no developers know of it and it isn't such a great advantage after all.
..................Content has been hidden....................

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