When working with the String primitive type in JavaScript, you've probably noticed it is not always an easy experience adding in variables or working with multi-line strings. In the ES6 edition of JavaScript one of the new features that was introduced to help with this problem was the Template Literal. A Template Literal is a new way to create a string literal that expands on the syntax of the String primitive type allowing for interpolated expressions to be inserted easily into strings.
When you finish this reading you should be able to interpolate a string using template literals.
To create a template literal, instead of single quotes (') or double quotes (") we use the grave character, also known as the backtick (`). Defining a new string using a template literal is easy - we can simply use backticks to create that new string:
let apple = `apple`;
console.log(apple); // apple
The important thing to know is that a template literal is still a String - just with some really nifty features! The real benefits of template literals become more obvious when we start talking about interpolation.
One of the main advantages we gain by using template literals is the ability to interpolate variables or expressions into strings. We do this by denoting the values we'd like to interpolate by wrapping them within curly braces with a dollar sign in front(${}). When your code is being run - the variables or expressions wrapped within the ${} will be evaluated and then will be replaced with the value of that variable or expression.
Let's take a look at that syntax by looking at a simple example. Compare how easy to read the following expressions are:
let name = "John";
console.log("Hello " + name + "!"); //=> "Hello John!"
console.log(`Hello ${name}!`); //=> "Hello John!"
name = "Jane";
console.log("Hello " + name + "!"); //=> "Hello Jane!"
console.log(`Hello ${name}!`); //=> "Hello Jane!"
As we can see in the above example, the value of the variable is being interpolated into the string that is being created using the template literal. This makes our code easier to both write and read.
You'll most often be interpolating variables with template literals, however we can also interpolate expressions. Here is an example of evaluating an expression within a template literal:
let string = `Let me tell you ${1 + 1} things!`;
console.log(string); // Let me tell you 2 things!
We can also use template literals to create multi-line strings! Previously we'd write multi-line strings by doing something like this:
console.log("I am an example
" + "of an extremely long string");
Using template literals this becomes even easier:
console.log(`I am an example
of an extremely long string
on multiple lines`);
How to use template literals to interpolate values into a string.