Make String Template in Javascript with “Template Literals”!!!

Strings can be much more than just a bunch of Characters using the ES6 Template Literals. Here’s how it works!

Harsh Prateek
3 min readJul 2, 2022
A stock image from unsplash
Photo by Ferenc Almasi on Unsplash

According to the Oxford dictionary, a Template means a shaped piece of rigid material that would be used in the processes of cutting out, shaping or drilling.

Before the advent of ES6, whenever we needed to use a string multiple times or were required to make changes in a String then this was the syntax we had to follow:

var sum = 2+2;var x = 'This string can change ' + sum + ' according to the value of sum';console.log(x);

This syntax does get the job done, although code readability is compromised big time by this syntax.

ES6 solved the problem of readability when the string changed with the help of its template literals.

Here is the same example, this time with the template-literal syntax:

let sum = 2+2;let x = `This string can change ${sum} according to the value of sum`;console.log(x);

The second example with the template literal is much more readable than the previous one.

The best thing is that it is a continuous string, while in the previous example, we had to break the String every time we wanted to introduce a variable in the String that changes the value. It becomes too tedious and error-prone when done with a string with many such variables.

The trick here is using back-ticks `` and the dollar signs $ with braces {}. By using these symbols, we can easily make a template literal.

Here’s the syntax with VSCode syntax highlighting. The syntax highlighting makes it way too easy.

If it were for the older method, we would have made two strings and joined them with the variable between them. This method of the template literal makes the code more readable, as evident from the above image.

Here is an example of using functions in the template literals:

This example above uses a function that returns a sum of two numbers.

Conclusion:

This article was a part of my series about the necessary topics to be done before learning ReactJS. I recommend checking this article if you also want to start with ReactJS. I hope you enjoyed this short article about template-literal in Javascript.

Follow me on Medium and Twitter if you want to know all the latest information I post about Coding.

Have a nice day😊.

--

--

Harsh Prateek

Hi, I am Harsh and I write about coding and learning techniques. I am a student myself and would love to tell everyone my secrets for coding and learning.