# Goodbye Plus Sign: A Beginner's Guide to JavaScript Template Literals

If you’ve written even a little bit of JavaScript, you are probably very familiar with the plus sign (`+`). For a long time, using the `+` operator was the only way we could glue words and variables together in our code.

Sure, it gets the job done. But as your code grows, old school string concatenation quickly turns into a messy, confusing headache.

Before modern JavaScript gave us a better way, developers had to fight with a few very frustrating problems. Let's look at why the old way of handling strings was so painful.

# Problems with traditional string concatenation

## 1\. The "Plus Sign" Soup (No String Interpolation)

In modern programming, it’s nice to just drop a variable directly inside a sentence. But older JavaScript couldn't do that.

Instead, if you wanted to put a user's name inside a greeting, you had to chop the sentence into little pieces and glue them together with plus signs. It makes the code really hard to read, and it is incredibly easy to forget a blank space.

```javascript
var name = "Janvhi";
var marks = 3;

var message = "Hello " + name + ", you scored " + marks + " marks in maths test.";
```

## 2\. Quote Hell: Single vs. Double Quotes

If you want to write HTML inside your JavaScript, or just use an apostrophe (like in the word "don't"), you run into a big problem.

If you start a string with a double quote (`"`), you can't use another double quote inside it unless you put a backslash (`\`) in front of it. It requires us to juggle constantly between single and double quotes, which usually resulted in broken code and a lot of frustration.

```javascript
var className = "primary-button";

var buttonHtml = "<button class=\"" + className + "\">Don't click me!</button>";
```

## 3\. The Multiline Problem (The Dreaded `\n`)

Have you ever tried to write a simple paragraph in old JavaScript? If you press "Enter" on your keyboard to start a new line, your code breaks.

Old strings did not understand multiple lines. To make text go to the next line, you had to manually type `\n` exactly where you wanted the line break. It made formatting emails or blocks of text a nightmare.

```javascript
var email = "Dear User,\n\n" +
            "Thanks for signing up.\n" +
            "Please verify your email.\n\n" +
            "Thanks!";
console.log(email)
```

## 4\. JavaScript Gets Confused (Unexpected Math)

The `+` symbol is used for two completely different things: adding numbers together (math) and gluing strings together (text).

Because of this, JavaScript sometimes gets confused. If it sees text anywhere in your equation, it might decide to turn your numbers into text, too. This is called "type coercion," and it causes sneaky bugs.

```javascript
var price = 10;
var tax = 2;

// You want 12, but JavaScript glues the numbers like words.
console.log("Your total is $" + price + tax); 
// Output: "Your total is $102" (But 10 + 2 is not 102)
```

### 5\. Old Strings have No Tagged Templates

Finally, old school strings are just plain text. You can't easily run them through a function to clean them up.

# What is template Literals ?

**Template literals** are a feature introduced in modern JavaScript (ES6) that make working with text (strings) significantly easier.

Instead of using standard single (`'`) or double (`"`) quotes to create a string, template literals use **backticks** (`` ` ``). The backtick key is usually located at the top-left of your keyboard, right under the Escape key.

## **The Magic Combo: ${}**

When you put a dollar sign and curly brackets together inside a template literal, you create what developers call a placeholder (or string interpolation).

**The Dollar Sign ($):** This acts like an alert. It tells JavaScript, "Hey, stop reading this as plain text for a second!"

**The Curly Brackets ({}):** These act like a little window into your JavaScript code. Anything you put inside these brackets is treated as actual, running JavaScript, not just letters in a sentence.

Because of this ${} combo, you no longer have to chop up your strings and glue them together with plus signs. You can just drop your variables right into the middle of the sentence.

**Example: Dropping in a variable**

```javascript
let favoriteSnack = "pizza";

// The ${} creates a window to grab the variable's value
let message = `My absolute favorite food is ${favoriteSnack}.`;

console.log(message); 
// Output: "My absolute favorite food is pizza."
```

### **It’s Not Just for Variables!**

Because that little window ({}) accepts any valid JavaScript, you don't just have to put variables in there. You can actually do math, run functions, or check conditions right inside the string.

**Example: Doing math inside the string**

JavaScript

```javascript
let price = 10; 
let tax = 2;

// JavaScript calculates the math inside the ${} before creating the sentence! 
let receipt = Your total cost is $${price + tax}.;

console.log(receipt); 
// Output: "Your total cost is $12."
```

By switching to Template Literals, you unlock major superpowers that traditional strings don't have:

## 1\. String Interpolation (No More Plus Signs)

This is the biggest benefit. Instead of chopping up strings and gluing them together with the `+` operator, template literals let you inject variables and math directly into the text using a dollar sign and curly braces: `${}`.

### **The Old Way:**

```javascript
let name = "Janhvi";
let age = 20;
let greeting = "Hello, my name is " + name + " and I am " + age + " years old.";
```

### With Template Literals:

```javascript
let name = "Janhvi";
let age = 20;
// Just wrap the variables in ${} right inside the backticks!
let greeting = `Hello, my name is ${name} and I am ${age} years old.`;
```

## 2\. Native Multiline Strings

With traditional strings, if you wanted to format text across multiple lines, you had to manually type the `\n` character everywhere. With template literals, you just press the `Enter` key on your keyboard. JavaScript respects the exact spacing and line breaks you type inside the backticks.

### **The Old Way:**

```javascript
let poem = "Roses are red,\n" +
           "Violets are blue.";
```

### **With Template Literals:**

```javascript
let poem = `Roses are red,
Violets are blue.`;
```

## 3\. No More "Quote Hell"

Because template literals use backticks, you can freely use single quotes and double quotes inside your text without confusing JavaScript or having to "escape" them with backslashes ().

### The Old Way:

```javascript
let html = '<div class="header">Don\'t click me!</div>';
```

### **With Template Literals:**

```javascript
let html = `<div class="header">Don't click me!</div>`;
```

## 4\. Tagged Templates

In modern web development, we often need to check strings for security reasons (like removing bad code a user might have typed in) or translate them into different languages. With traditional concatenation, doing these advanced tasks requires writing a lot of extra, clunky code. Modern JavaScript introduced features (like Tagged Templates) to handle this automatically, but old strings simply can't use them.

```javascript
const person = "Janhvi";
const age = 28;

function myTag(strings, personExp, ageExp) {
  const str0 = strings[0]; // "That "
  const str1 = strings[1]; // " is a "
  const str2 = strings[2]; // "."

  const ageStr = ageExp < 100 ? "youngster" : "centenarian";

  // We can even return a string built using a template literal
  return `${str0}${personExp}${str1}${ageStr}${str2}`;
}

const output = myTag`That ${person} is a ${age}.`;

console.log(output);
// That Janhvi is a youngster.
```

# At a Glance Table

| Feature | Before (Traditional Strings) | After (Template Literals) |
| --- | --- | --- |
| **Basic Syntax** | Uses single (`'`) or double (`"`) quotes. | Uses backticks (`` ` ``). |
| **Inserting Variables** | **"Plus Sign Soup"**  
Requires chopping strings and using the `+` operator.  
*(e.g.,* `"Hello " + name`*)* | **String Interpolation**  
Drop variables directly inside using `${}`.  
*(e.g.,* `Hello ${name}`*)* |
| **Multiline Text** | **Manual & Messy**  
Breaks if you press "Enter". Requires manually typing `\n` for every line break. | **Native Support**  
Just press "Enter". Respects exact spacing and line breaks automatically. |
| **Using Quotes Inside** | **"Quote Hell"**  
Juggling single/double quotes or escaping them with backslashes (`\"`). | **Use Freely**  
Single (`'`) and double (`"`) quotes can be used inside backticks without escaping. |
| **Doing Math** | **Type Coercion Bugs**  
JavaScript gets confused and glues numbers like text.  
*(e.g.,* `10 + 2` *becomes* `102`*)* | **Safe Math**  
Math inside the `${}` window is calculated *before* becoming text.  
*(e.g.,* `${10 + 2}` *becomes* `12`*)* |
| **Advanced Parsing** | **Plain Text Only**  
Cannot easily pass the string through a function as it is being built. | **Tagged Templates**  
Can run the template through a custom function to clean, translate, or format the text. |

# **Wrapping Up**

If you are still using the old plus sign to glue your JavaScript strings together, today is a great day to stop!

Template literals might look a little strange at first because of the backticks and dollar signs, but once you get the hang of them, you will never want to go back. They make your code cleaner, easier to read, and much less likely to break.

Also stay tune for the next Blog!!
