What are Template Literals in JavaScript
Codecupdev
Posted on May 21, 2022
What are Template Literals?
In the ES6 version of JavaScript, template literals were introduced. Before ES6 if we had a variable that we wanted to use within our strings we would have to do something like the following example.
function printDrink() {
var drink = "Tea";
return "My favourite drink is" + " " + drink;
}
console.log(printDrink());
//Returns ---> My favourite drink is Tea
In the above example, we create a function declaration called printDrink. Inside the function, we create a variable called drink. We assign to the variable the string “Tea”. The function returns a string which uses concatenation (the addition symbols) to print out a string and the drink variable. When the function is invoked we get the string returned.
Template literals offer a clean way to interpolate (inject) the variables or expressions into the string as opposed to having to do the concatenation. A template literal is enclosed in back-ticks instead of the usual double or single quote marks. String interpolation describes when variables are injected into a string. The variable you wish to interpolate is wrapped inside curly braces and started with a dollar sign. The variable itself is placed inside the curly braces.
Let’s look at the prior example but this time using a template literal.
function printDrink() {
var drink = "Tea";
return `My favourite drink is ${drink}`;
}
console.log(printDrink());
//Returns ---> My favourite drink is Tea
In the above example we keep the same function declaration and drink variable. This time we use a template literal. The template literal is enclosed within back ticks and returns the string. Using interpolation the drink variable is injected into the template literal. When the function is invoked we get the same return value.
Multi line strings
Another useful feature of template literals is that we can span our string over multiple lines. Prior to ES6 you would have to either use string concatenation or a new line character (\n) to achieve this. I briefly show an example of this below:
var ourString = "First line\nSecond line\nThird line\n";
console.log(ourString);
//Returns --->
First line
Second line
Third line
With template literals we no longer have to worry about this. If we want to create a multi line string we can do so by enclosing the string in back ticks and separating the lines.
let ourString = `First line
Second line
Third line`;
console.log(ourString);
//Returns --->
First line
Second line
Third line
I hope you enjoyed this article! If you would like to watch a video tutorial it is available here.
Posted on May 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 6, 2024