Template Strings

In some languages, you assemble a string out of smaller pieces using concatenation:

String message = "You have " + messageCount +
" new message" + (messageCount == 1 ? "" : "s") +

That's messy. Balancing the quotation marks is annoying. A cleaner way is to use a format string with % placeholders:

String message = String.format(
"You have %d new message%s.",
messageCount == 1 ? "" : "s"

JavaScript doesn't have builtin support for format strings. However, it does have template strings. You may embed expressions directly inside the string literal by enclosing the expressions in ${}:

const message = `You have ${messageCount} new message${messageCount == 1 ? 's' : ''}.`;

A template string is delimited by backticks (`) rather than single- or double-quotation marks. As soon as this assignment statement is reached, any embedded expressions between the backticks are evaluated, and their values are substituted into the string that is assigned to message.

Template strings are often cleaner than concatenation. But they one-up them in another way: they can span multiple lines:

const formLetter = `Dear ${boss}:

By the time you receive this message, I will have
quit. I have found a startup that is friendly to



Any internal newlines or indentation are really in the string.

HTML inside JavaScript is much more readable when you spread it across multiple lines of a template string:

container.innerHTML = `
<img src="
${image.path}" alt="${image.description}">

Try writing a template string in your browser's console to produce a message of this form:

The hypotenuse of 5 and 12 is 13.

Do not hardcode the numbers into the string. Use embedded expressions.