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 (“”).


let hello = `Hello World!`;

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.


The syntax is:


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.


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

Quotes Within Strings

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


let name = `He's frequently referred to as "Roger."`;

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"

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

console.log(`Say hello to 
// "Say hello to
// multi-line
// strings!"

Variable Substitution

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


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

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

Expression Substitution

Template literals also allow expressions in strings:


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

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.

Pin It on Pinterest