# Template Literals in JavaScript Explained with Examples

Before we know what template literals are, it is important to know why template literals were introduced and what was used before template literals was introduced. What were the problems with the earlier method? Let's first discuss that.

## Why Template Literals was introduced?

Before template literals was introduced, developers used the `+` operator to join strings.

```javascript
let name = "Ayush";

console.log("Name: "+ name);
//Output --  Name: Ayush
```

## Problems with `+` Operator

### 1\. Poor Readability

As strings become longer, concatenation becomes messy.

```javascript
const text =
  "Hello " +
  name +
  ", welcome to our website. Your account balance is " +
  balance +
  " rupees.";
```

### 2\. Multi Line string

before Template Literals

```javascript
const message =
  "Line 1\n" +
  "Line 2\n" +
  "Line 3";
```

we had to use /n for every line.

### 3\. Easy to make mistakes

missing spaces

```javascript
let name = "Ayush"
console.log("Hello" + name)
//Output -- HelloAyush
```

these types of mistakes were very common

## What are Template Literals?

Template literals were introduced with ES6 in 2015.

Now instead of ( ' ' ) and ( " " ) back ticks ( \` \` ) are used to define a string and this allowed writing a variable inside a string ( string interpolation) without using the operator.

![](https://cdn.hashnode.com/uploads/covers/6957b06e6e38b6011157e5c8/956bb7cc-b4e0-476c-8fce-da7d7a403ddf.png align="center")

```javascript
const name = "Ayush";

const message = `Hello ${name}`;

console.log(message);

//Output -- Hello Ayush
```

### Syntax of template literals

Basic syntax

```javascript
`Text here`
```

With variable

```javascript
const language = "JavaScript";

console.log(`I am learning ${language}`);

//Output -- I am learning JavaScript
```

### Multi Line String

template literals allow you to write multi-line strings directly.

Without Template Literals:

```javascript
const text =
  "Hello\n" +
  "Welcome\n" +
  "To JavaScript";
```

With Template Literals:

```javascript
const text = `
Hello
Welcome
To JavaScript
`;
```

## Real-World use cases

### Generating Dynamic Messages

```javascript
const username = "Ayush";

const greeting = Welcome back, ${username}!;
```

### Building URLs

```javascript
const userId = 123;

const url = /users/${userId};
```

### Dynamic CSS Classes

```javascript
const active = true;

const className = `btn ${active ? "active" : ""}`;
```

Used extensively in React.

## Key Takeaways

*   Template literals were introduced in ES6.
    
*   They use backticks ( \` \` ) instead of quotes.
    
*   `${}` allows string interpolation.
    
*   They improve readability compared to `+` concatenation.
    
*   Multi-line strings become much easier to write.
    
*   Widely used in React, URLs, and dynamic UI rendering.
