# Template Literals in JavaScript

# Introduction

> Everything you see in a browser - except images and videos- is a string.
> 
> \-Andrey Germanov

The "String" is an important component in any programming language, not only javascript. Thus, it becomes quite necessary to understand and manipulate the `String` data type. A string in our computing biz or industry refers to a string or arrangement of characters.

*   `Characters`: A character in programming is a fundamental data type (`char`) representing a single symbol—such as a letter ('A'), digit ('1'), or punctuation ('$')—used to store and manipulate text. It is encoded as a numeric value using standards like ASCII or Unicode. Characters are the building blocks of strings and occupy a small, fixed amount of memory (typically 1 byte).
    

So, now I hope you understood what a string is. I hope...

# String in Programming

I have quite some experience regarding declaring and using strings in multiple programming languages, since it is the first thing they teach you in the CS101. Here are common syntax used in some of the programming languages:

```java
String str = "Hello People";
//In java String keyword is used to declare strings.
```

```python
str = "Ello there mate"
#In python simply using quotes(' or ") is interpreted as strings
```

And now in our beloved JS:

```javascript
const str = "The quirky JS"
//In JS also, we only require quotes to make the variable a string
```

These are only some ways to declare a string, and while there are also other ways through which you can play around with `String` we shall refrain from using them as they are not our concern today, for we must move forward with our topic of the day, that being the ***String Interpolation.***

# Traditional String-ing

*   Interpolate: To add something to a piece of writing
    

Before ES6(ECMAScript 6th Edition) was released in June 2015, we had only one way to interpolate with strings and that method quite resembled what all the other languages were using at the time. It went something like this:

```javascript
const words = "Well, this isn't efficient";
console.log("This is...\n" + words + " is it?");
```

In the above example code snippet, you should see that in order to insert a variable inside a string you implement a '+' symbol. Also if you want to create a multiline string, a keyword is written `\n` the infamous backward slash n.

This method had several Issues.

## Issues with old String handling

1.  Low Readability: The previous way really compromised readability due to its operating rules. You would need to pay attention to '+' and also reserved keywords such as '\\n' and '\\t' meaning tab. This becomes quite a hassle when you consider how much as programmers we need to deal with the strings in our daily life.
    
2.  Complexity: As we can see, the old way was responsible for immediately increasing complexity of our codebases.
    
3.  Problem with "": The quotes themselves proposed a problem, as language is just-in-time compiled it sees " between strings as the end of it and not as a part of it. E.g. `console.log("Hi I'm "Alok"");` And before you know it errors are in your room sipping chai. This meant an overreliance on the special string keywords.
    

1.  Error Prone: The increased complexity and low readability invites Errors and bugs like bugs are attracted to candles. This analogy works in layers.  
    

This problem got its remedy in the form of ***Template Literals.***

# Template Literals

In the update of ES6, in June 2015, the JS got a massive update in the form of Template Literals. We have seen how in JS, in order to declare a variable as a string we used quotes("" or ''), but with upcoming template literals we changed a bit of our syntax, as we shifted to Backticks(\`\`).

```javascript
const words = `The improved method`;
console.log(`Template Literals is the ${words}`;
//Simple variable insertion through the ${...}.
```

## Syntax Shifting

A basic table here would suffice to understand before and after template literals.

| String Concatenation | Template Literals |
| --- | --- |
| We used quotes, such as '...' or "..." to declare a string. | We rely on Backticks, they look like \`\` to declare and use a string. |
| Low Readability. | Improved Readability. |
| Increased complexity. | Reduced complexity. |
| Error Prone. | Not as much error prone. |
| In order to insert variables we used '+' between two quoted string snippets. For ex. `"Here " + str`. | In order to insert variable we use ${} inside backticks. For ex. `Here ${str}`. |
| Multiline meant using a bunch of \\n in the string and then relying on the sharper eyes to detect where they are inserted. `This is \npseudo multi \nline`. | Simply using `enter` to push the line down works.  
`` `This   is   Multiline` ``. |

*   `${}` also allows us to perform mathematical operations inside it. And functions call and execution as well.
    

```javascript
console.log(`Hearts beating ${3 * 2} times`);
//Operations inside the ${...}
```

## Syntax

*   Declaration: The declaration is simple with Backticks(\`\`).
    

```javascript
const str = `Easy declaration`;
//Declaration was not that difficult in concatenation either
```

*   Variable Embeddings: Inserting variables is done inside backticks only(\`\`). We simply use `${}` symbol.
    

```javascript
const str = "World";
console.log(`Hello, ${str}`);
//The variable is simply inserted using ${}. 
```

*   MultiLine: The multiline in concatenation required a bunch of `\n` backtick slash n's. In Template literals, the way we write code with shifted action is how it is compiled and printed.
    

```javascript
const oldWay = "Multi \n Line";
const newWay = `
                Multi
                Line`;

//Guess which one is Simple and effective... 
```

## Modern Day Uses

1.  Using template literals to render HTML pages.
    

```javascript
const element = `<div>${user}</div>`;
```

2.  Expression Interpolation: Inside the `${...}` we get to implement Math and Logic, as well as Ternary Operators and function calls as well.
    
3.  MultiLine Strings are intuitively implemented.
    

# Conclusion

The template literals were one of those features that changed how we played the game. It has now become the default way of handling `Strings`.

Now at last I thank team ChaiCode for this opportunity. I can't believe that the teachers are this dedicated any place.
