Sub topic 1
Writing Strings with Backticks
Prerequisites
This chapter assumes you already know:
- JavaScript variables, expressions, and functions
- Regular string literals written with single and double quotes
- Common array methods such as
mapandjoin
Writing Strings with Backticks
A template literal is a string literal wrapped in backticks (` ``) instead of quotes. It produces an ordinary string. The difference is in what you can put inside it.
const a = 'plain';
const b = "plain";
const c = `plain`;
console.log(a === b && b === c); // true
console.log(typeof c); // stringSingle and double quotes can appear inside backticks without escaping. This makes text such as ` It's "fine" ` easy to write.
Embedding Expressions with ${}
Inside a template literal, ${expression} evaluates the expression and inserts its result into the string. Any expression is allowed: variables, arithmetic, function calls, or ternaries.
const name = "Ada";
const count = 3;
console.log(`Hello, ${name}! You have ${count * 2} new messages.`);
// Hello, Ada! You have 6 new messages.
const items = 1;
console.log(`${items} ${items === 1 ? "item" : "items"}`);
// 1 itemThe expressions are evaluated left to right when the literal runs, and each result is converted to a string. A later chapter covers the conversion rules.
Multiline Strings and Their Whitespace
A template literal can span several lines. Every line break and every space inside the backticks becomes part of the string, and that includes the indentation of your source code.
function message() {
const text = `
Dear user,
Welcome back.
`;
return text;
}
console.log(JSON.stringify(message()));
// "\n Dear user,\n Welcome back.\n "The result starts with a newline, carries four spaces of indentation on each line, and ends with two spaces. If you need exact output, build the lines yourself or trim the result:
const lines = ["Dear user,", "Welcome back."];
console.log(JSON.stringify(lines.join("\n")));
// "Dear user,\nWelcome back."
const trimmed = `
Dear user,
Welcome back.
`.trim();
console.log(JSON.stringify(trimmed));
// "Dear user,\nWelcome back."trim() removes whitespace only at the two ends of the string. It does not remove indentation in the middle lines, so write those lines flush left when the whitespace matters.
Exercise
With const a = 2, b = 3;, what does ` console.log(${a} + ${b} = ${a + b}) ` print, and what would it print if the backticks were replaced with double quotes?
Show answer
With backticks it prints 2 + 3 = 5. With double quotes there is no substitution, so it prints ${a} + ${b} = ${a + b} exactly as written.
Exercise
What is the length of the string ` ab
c ` (the second line starts with two spaces)?
Show answer
6. The string holds "a", "b", a newline, two spaces, and "c".