ES6: Template Literals

Keji Amos
Keji Amos
Aug 23, 2017 · 3 min read

What are they?

Template literals are simply another way of creating a string in Javascript. Instead of using single or double quotes, developers can use grave accents or back-ticks, (``).

Creating a string with quotes

What’s so great about them?

Template literals improve the readability and construction of strings. Using quotes meant you needed to stop your string, concat onto the string to add a variable then you had to restart your string. Don’t forget to add those blank spaces between your variables. Yeah, that’s a hassle.

When we use the back-ticks everything we pass in gets sent to a function that will do all of the concatenation for us. That means less time debugging the formatting of the string. We get some new syntax with ${} which is how we pass in variables to get interpolated into the string.

Another nicety is you can create multi-line strings without using the newline escape character (\n). This is because the newline character is built into template literals.

Template literal multi-line string

Use Javascript inside a template literal!

There’s more to template literals than just making multi-line strings and interpolating variables. You can do anything with Javascript inside a template literal, like running a function or nesting more template literals.

Looping

You want to create a list of food items from an already existing array of food items you can do that like this:

Looping

If we breakdown this example even further you can see that we have not only looped over our food array but we’ve created HTML elements as well. If you’re familiar with React this could look something like this:

Level Up: Tagged Template Literals

You can pass your template literals into functions. Here’s what this looks like:

Tagged Template Literal

How this works is, when you pass the template literal into the function the function breaks it down into a few different parameters. The first is an array of strings. In the previous this would be ‘My name is’. Then every variable wrapped in ${} will act as an additional parameter

When all is said and done print will be assigned whatever is returned from function doSomething, it doesn’t have to be string. The possibilities are endless for what you can do with a tagged template literal but that’s the gist of how they work.

Final words

Use template literals. They’re going to help reduce the amount of bugs to track down and provide some interesting possibilities with the ability to run Javascript directly and pass them into functions.

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade