Published on 06/18/2020
Up until now, we only had two ways to write a string in JavaScript - single and double quotes. If we wanted to interpolate a variable with one of these string options, we'd need to break out of the string and concatenate the variable.
As of ES2015, we are able to use Template Literals. These are string literals that allow embedded expressions.
Instead of single or double-quoted strings, we can enclose our strings with back-ticks, which allows for variable interpolation without breaking out of the string.
For example:
In addition to interpolation, another feature of Template Literals, that wasn't available before, is that you can now easily create multi-line strings without having to escape them.
Prior to this feature, you needed to escape each return, as follows:
This is handy when creating HTML markup to output as a string. Note that the whitespace will be output as well, but this isn't really problematic since the whitespace is ignored as soon as it hits the HTML.
The last thing to note here is that you can nest template literals within each other by wrapping the nested templates in the same ${} placeholder that we use to interpolate variables.
In the example above we have a template string that is nested inside a template string. With this, we can easily loop over and render the list items without breaking out of the containing string.
Side note: since map() returns an array, we pass it to join() and join it on an empty string to get rid of the commas in the output.
---
Category: JavaScript
Tags: javascript, esnext