DEV Community

Max Lockwood
Max Lockwood

Posted on • Originally published at maxlockwood.dev

What are JavaScript Template Literals?

What are JavaScript Template Literals?

Template literals are literals delimited by backtick (``) characters that enable multi-line strings, string interpolation with embedded expressions, and tagged templates.

Back-Tics Syntax

To define a string, Template Literals use backticks (``) rather than quotes (“”).

Example

let hello = `Hello World!`;
Enter fullscreen mode Exit fullscreen mode

Why use template literals in JavaScript?

Template literals make it simple to convert variables and expressions into strings. String interpolation is the name given to this technique.

Interpolation

The syntax is:

${...}
Enter fullscreen mode Exit fullscreen mode

How to use ${} in JavaScript?

A placeholder is represented by ${] It allows for the introduction of a variable without concatenating. This is done using ${var} to add the variable string in-line to your current string.

Example

var location = 'bar';
console.log(`Let's meet at the ${location}`);
// Let's meet at the bar
Enter fullscreen mode Exit fullscreen mode

Quotes Within Strings

Within a string, you can use both single and double quotes with template literals:

Example

let name = `He's frequently referred to as "Roger."`;
Enter fullscreen mode Exit fullscreen mode

Multiline Strings

Multiline strings are supported by template literals.

Using normal strings, you would have to use the following syntax in order to get multi-line strings:

console.log("string text line 1\n" + "string text line 2");
// "string text line 1
// string text line 2"
Enter fullscreen mode Exit fullscreen mode

Using template literals, you can do the same with this:

console.log(`Say hello to 
multi-line
strings!`);
// "Say hello to
// multi-line
// strings!"
Enter fullscreen mode Exit fullscreen mode

Variable Substitution

With template literals, it’s a bit easier to include variables inside a string. For that, we use the ${...}syntax.

Example

let firstName = 'Paul',
    lastName = 'Smith';

let greeting = `Hi ${firstName}, ${lastName}`;
console.log(greeting); // Hi Paul, Smith
Enter fullscreen mode Exit fullscreen mode

Expression Substitution

Template literals also allow expressions in strings:

Example

let a = 10;
let b = 20;
console.log(`Result = ${a + b}`); // Result = 30
Enter fullscreen mode Exit fullscreen mode

The process of assigning variables and expressions inside the template literal is known as interpolation.

Further reading

Want to learn more about Template literals then check out: Template literals | MDN

See also

What is the Syntax of JavaScript?
How to Display Output in JavaScript
What are the Three Variables in JavaScript?

If you liked this article, then please share. You can also find me on Twitter for more updates.

Top comments (0)