Remember the time when you had to insert variables in a string and how awful it was? And how the times you had to use ‘ ’ and the sign +. You ran your code and the spacing between variables was off or, even worse, you forgot a + sign and the code didn’t work properly. 

There’s a solution implemented in ES6 called Template literals and here’s how it works.

What Is a Template Literal?

The MDN definition is “Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.”  Fancy definitions aside, a template is a preset format and a literal is a value written exactly as it’s meant to be interpreted. In JS terms a template literal is a way to concatenate strings while allowing embedded expressions and improving readability.

To write a template literal just use a back-tick instead of a single or double quotes, like this,

String Interpolation

Forget about the pain of interpolating strings and variables, template literal solves this issue with string interpolation. Just embed an expression like this “${expression}”. 

Take a look at the examples below,

Analyzing these two examples, we can see that using template literals helps us have clean code and better readability.

Another area where template literals work like a charm is whenever there are line breaks,

No more \n and all that nonsense that made our head hurt. Now let’s embed a function right into our template literal,

Here’s how you can use all of these features at once. Add HTML to a page using JavaScript and template literals,


Template literals make our strings with variables and embedded expressions easier to write, and easier to identify errors.

They are powerful because they give you an interesting and easy way to use strings. It may be hard to get used to them but once you do, there’s no coming back.

Got any question or comment? Send me an email at  [email protected]