The thing with JavaScript Template literals
Tags: javascript, string
Published: 2022-02-27 12:55:14

Template literals in JavaScript are depicted by back ticks **``**.
They are useful because they help us to include variables and functions within a sentence without the need for truncating and joining. What do I mean?
####Example 1a:
######Without Template Literals``
```
var belligerent1 = 'NATO'
var belligerent2 = 'Russia'

var sentence = 'Upheaval in Europe as ' + belligerent1 + ' and ' + belligerent2 + ' attempt a showdown'
```

As you can see from the above example, our sentence needed the values of the variables `belligerent1` and `belligerent2` for its message to be complete.
Without template strings, we truncate the strings at the point where we need to insert the variable, use the `+` operator to join the variables to our strings, so that in the end we have a complete sentence.

---

With Template literals, you can rewrite the sentence without the need to truncate and join.
####Example 1b:
######With Template Literals

```
var beliigerent1 = 'NATO'
var belligerent2 = 'Russia'

var sentence = `Upheaval in Europe as ${belligerent1} and ${belligerent2} attempt a showdown`
```

The rewritten version above, shows a string with variables included that is not using the `+` operator and yet is full and complete. Thanks to template literals.
By enclosing your string with back ticks **``**, JavaScript uses **${ }** to embed variables and functions into the string. And so with back ticks, you can write full sentences having variables, and functions, without the need to truncate and join.
####Example 1c
######With Template Literals``
```
var belligerent1 = 'NATO'
var belligerent2 = 'Russia'
function takeAction(value) {
 if (value == 'pressure') return 'charge'
 if (value == 'reflect') return 'retrace steps'

 return 'deliberate some more'
}

var sentence = `Upheaval in Europe as ${belligerent1} and ${belligerent2} attempt a showdown. Certainly, one of them, soon or late, will ${takeAction('reflect')}`
```
A third example with function included just for the good of it.

---

###So what is it with Template Literals??
It is in when you're trying to make a perfect replica of a string, maybe for example, in a software testing scenario.
Generally, strings are tricky to reproduce. Some may have spaces or next lines (\n), or the lack of them, which your eye did not quite catch, and so you code your string, but the test script does not agree with your submission. And thus, these features, such as spaces, next lines, if present or absent, can be the make or break between the app accepting your submission, as the string it wants.

Obviously, the longer the string, or where there are paragraphs in a string, the higher the chances of a miss in reproducing it perfectly.
Template literals, in addition to being employed for conveniently including variables and functions in strings, they are also employed, quite often too, when strings are long and have paragraphs.
Normal string quotes '' or "" cannot make paragraphs within the string with the `ENTER` key on the keyboard. One has to encode the paragraph with \n, and generally continue typing on the same line. See the tip below.
#####Tip:

> whether you're using template strings or normal quotes, you can wrap your string onto the next line with the escape character `\`. The escape character is really a handy tool in strings and regex.

The template string differs again from normal quoted string in that it recognizes the `ENTER` key of your keyboard and allows you to make paragraphs without the need to use \n. Here in this its strength also lies its slippery slope.

When you code in a string of multiple lines enclosed in template literals, you may miss some spaces and paragraphs that are contained therein. Especially if this string is to be the exact replica of another written string. Also
* Your code editor may format your code and introduce unwanted spaces in your string
* Every `ENTER` key press you make in your template string, is a \n introduced
* When you print your string, you may not observe some of the extra spaces you have introduced by yourself, yet if the string is to match another, then it's very important to be aware of why the match might be bringing up a fail even when the two strings look very much the same.

###Some steps to take to protect yourself from this GOTCHA
These steps are only necessary really, if the output pattern of your string is crucial to what you're doing or testing.
Here are some steps...
* If you simply mean to wrap your code to the next line, while in a template string, use the escape character `\`

Example:
```
const foodStatus: `There's still rice. There's beans, but there's \
no more meat, no plantain, and no egg.`
```
Observe that I did not put the beginning of the sentence in a new line, away from its opening quote. That would have literally created a \n at the top of the string, and that is not my intention.
* Where there are no variables of functions to be included, you could opt for normal quoted strings entirely.
Example:
```
const foodStatus: "There's still rice. There's beans, but there's no more meat, no plantain, and no egg."
```
* Combine template literals with normal quoted strings. You use the template literals where you need to get in the variables and functions, and normal quotes where only strings are involved. Yes, you will use the `+` operator to join them. But at least you can be super certain of every space and \n that exists in the string, as you will ensure no string wraps into the next line. More so, you will preserve your code formatting style this way.
Example:
```
function takeAction(value) {
 return (
`There are ${(2 > 1) ? 2 : 'no'} yam${true ? '' : 's'}` +
' in the farm barn, ' +
`but there are ${(5 % 2 == 0 ) ? 5 : 30} egg${false ? '' : 's'} of beer.\n` +
' enough to go round.'
)
}
```
This way, the `ENTER` key pressed outside any of the quotes don't add any \n. And you're confident of where all spaces and \n are.

Thank you for reading.