ES6 - Template Literals (Template strings)

ES6 - Template Literals (Template strings)

ES6 JavaScript

Share

In this ES6 JavaScript tutorial we will learn about Template Literals (Template strings).

What are Template Literals?

Template literals are string literals that allows us to embed expressions, multi-line strings and string interpolation.

Template literals are enclosed using backtick ` ` instead of single quotes and double quotes.

Let's print the string Hello World using single and double quotes.

console.log('Hello World');
console.log("Hello World");

Now, let's print the same string using template literal.

console.log(`Hello World`);

Embed expression in template literals

We can embed expression using dollar sign and curly brackets like the following ${expression}.

In the following example we are printing a string "Sum 2 + 3 = 5".

console.log("Sum 2 + 3 = " + (2 + 3));

The above code will print the following output.

Sum 2 + 3 = 5

In the following example we are printing the same string using template literal.

console.log(`Sum 2 + 3 = ${2 + 3}`);

In the above code the expression ${2 + 3} is evaluated and it is replaced by the result 5.

Variables in template literals

In the following example we are using variables to print result.

var result = 2 + 3;
console.log('Sum 2 + 3 = ' + result);

The above code can be refactored using template literal like the following.

let result = 2 + 3;
console.log(`Sum 2 + 3 = ${result}`);

To learn more about the let keyword check out the ES6 - var let const tutorial.

Function call in template literals

We can even call function in template literal like ${functionName()}. In the following example we are calling a function using template literal.

function add(x, y) {
  return x + y;
}

console.log(`Sum 2 + 3 = ${add(2, 3)}`);

In the above code the expression ${add(2, 3)} is evaluated. So, it calls the add function with the two arguments 2 and 3. The add function then returns the sum 5. So, the expression is replaced with 5 and we get the following output.

Sum 2 + 3 = 5

Multi-line strings

To print multiple lines we can do the following.

var str = "This is the first line.\n" +
"This is the 2nd line.";

console.log(str);

The above code will print the following output.

This is the first line.
This is the 2nd line.

The same code can be refactored using template literal to print multiple lines.

const str = `This is the first line.
This is the 2nd line.`;

console.log(str);

Alright, this brings us to the end of this tutorial. Don't forget to practice. And if this was helpful then do share. Thanks for reading. See you in the next tutorial.

Share