String Interpolation in JavaScript: A Complete Guide

In programming, there is often a case where we want to print out a complete sentence but there are some values of some variables that are unknown to us, or that might frequently change since they are variables. Then we can use the string interpolation method to get the desired output. By string interpolation, we simply replace the placeholder variables with the calculated values at the time of production. JavaScript offers many functions and methods through which we can easily do string interpolation, especially since ES6. In this article let us take a look into that.

Also Read: Scope In JavaScript: Block, Function, Local, and Global

What is ES6?

All over the world people are using JavaScript to write code and keep in mind that JavaScript was written in only 7 days, there are some difficult problems when a team has to work on a single project. To make things easier ECMAScript was born, it is a standardization of JavaScript that helps us note the best practices while working together in JavaScript. The version of ECMAScript that came out in 2015 is known as ES6 or ECMAScript 6 since it is the 6th version of it. Today a lot of browsers support ES6 syntax and features so it is recommended to know and use these syntax and features.

What are template literals?

ES6 introduced a lot of literals to write code faster and easier. The main property of this is that the written code is very much similar to its output. Let us take an example:

let x = 5;
let y = x * x;

let answer = "The square of " +x+" is "+y;
console.log(answer);

In the above code block, we had to use string concatenation to get the desired output, notice the spaces inside the double quotes, without them the output would skip the spaces. This is hard to read and confusing when processing a lot of text. However, if we use the template literals (backticks “) we can make it easier to read. The code then becomes:

let x = 5;
let y = x * x;

//let answer = "The square of " +x+" is "+y;
let answer = `The square of ${x} is ${y}`;
console.log(answer);

The method we used before is known as a string literal.

Points to keep in mind when using String and Template Literals

Let us first see what the old way of working with strings was through a set of examples. First, let us see how to write a simple sentence and store it in a variable and print it out in the console. The code is as follows:

let sent = 'This is a sentence stored in a variable.'
console.log(sent);

We can also use single and double quotes inside the string and print them out. We can do this in two ways, the first way is to encase the string in the other quote type and use the other one in the string itself, what I mean by this is, if you use single quotes to encase the string, then you must use the double quotes to encase the quoted text inside the text. See the following example:

let doubleQuoted = 'This is a string where we use "double quotes".'
console.log(doubleQuoted);

And if you are using double quotes outside, then you must use single quotes inside:

let singleQuoted = "This is a string where we use 'single quotes'."
console.log(singleQuoted);

You can also use the single quotes inside the single quotes only if you escape those characters, like this:

let oldSentence = 'Hi \'this\' is how we escape characters.'
console.log(oldSentence);

As you can see this is very messy and easy to make a mistake. Also, let us take a look at string concatenation using the + operator:

let firstName = 'Writwik'
let lastName = 'Ray'
let fullName = firstName + ' ' + lastName;
console.log(fullName);

So much work just for the inclusion of a space between the first and last names. And if this is not enough there are linebreaks:

let oldLineBreak = 'Hi this is\na linebreak.'
console.log(oldLineBreak);

Reading the code in haste might result in missing the tiny \n escape character and confuse you completely when you check the output later.

So let us now take a look at what ES6 offers us as a solution to all these problems. In ES6 we can use the backticks when we want to use string literals. The new way of writing quotes is as follows:

let newSentence = `Hi 'here' we don't need to escape characters`
console.log(newSentence);

Also to include space we just include it in between the variable, no need to close the backtick and rewrite it again:

let newFullName = `${firstName} ${lastName}`;
console.log(newFullName);

Linebreaks are also much easier to read and implement:

let newLineBreak = `And this
is the new linebreak.`
console.log(newLineBreak);

Also, we must mention while using template literals we can simply add in the expressions inside ${} which will denote the value of the variable. We used this in the full-name example. To make it clear let’s make a simple tax deduction calculator:

let price = 100;
let tax = 0.20;
console.log(`Total: ${price * (1-tax)} Rs./-`)

The full code for the above examples is given below:

//let x = 5;
//let y = x * x;

//let answer = "The square of " +x+" is "+y;
//let answer = `The square of ${x} is ${y}`;
//console.log(answer);

let price = 100;
let tax = 0.20;

let sent = 'This is a sentence stored in a variable.'
console.log(sent);
doubleQuoted = 'This is a string where we use "double quotes".'
console.log(doubleQuoted);
let singleQuoted = "This is a string where we use 'single quotes'."
console.log(singleQuoted);
let oldSentence = 'Hi \'this\' is how we escape characters.'
let firstName = 'Writwik'
let lastName = 'Ray'
let fullName = firstName + ' ' + lastName;
let oldLineBreak = 'Hi this is\na linebreak.'

console.log(oldSentence);
console.log(fullName);
console.log(oldLineBreak);
console.log('Total: '+price*(1-tax)+' Rs./-');
console.log('\n#####END OF OLD OUTPUT#####\n');

let newSentence = `Hi 'here' we don't need to escape characters`
let newFullName = `${firstName} ${lastName}`;
let newLineBreak = `And this
is the new linebreak.`

console.log(newSentence);
console.log(newFullName);
console.log(newLineBreak);
console.log(`Total: ${price * (1-tax)} Rs./-`)
console.log(`
#####END OF NEW (ES6) OUTPUT#####
`);

Conclusion

This article covered everything about the string literals in JavaScript using the ES6 syntax. We hope you guys have understood and expanded your knowledge of JavaScript. For more such awesome articles, code, and examples make sure to keep on reading CodeForGeek. That’s all for this one, see you later!

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Writwik Ray
Writwik Ray
Articles: 7