Template Literals | Dataplexa

Template Literals

Working with text is very common in JavaScript. We often build messages, combine variables with strings, and display dynamic content on web pages.

Before ES6, handling strings could become messy. Template literals were introduced to make this easier, cleaner, and more readable.


What Are Template Literals?

Template literals are a modern way to work with strings in JavaScript. They use backticks (`) instead of quotes.

This allows you to embed variables and expressions directly inside a string.


Before Template Literals

Earlier, strings were combined using the + operator.


let name = "Alex";
let message = "Welcome " + name + " to Dataplexa";
  

This works, but becomes hard to read with more variables.


Using Template Literals

Template literals solve this problem by allowing expressions inside strings.


let name = "Alex";
let message = `Welcome ${name} to Dataplexa`;
  

The syntax is cleaner and easier to understand.


Embedding Expressions

Template literals can include full JavaScript expressions, not just variables.


let price = 100;
let tax = 18;

let total = `Total amount: ${price + tax}`;
  

The expression inside ${} is evaluated automatically.


Multi-line Strings

Template literals allow multi-line strings without special characters.


let message = `
Hello User,
Welcome to Dataplexa.
Happy Learning!
`;
  

This is very useful for messages, emails, and HTML templates.


Real-World Example

Displaying a user greeting on a website:


let username = "Sreekanth";
let greeting = `Hello ${username}, welcome back!`;

document.getElementById("greet").innerText = greeting;
  

Template literals make dynamic content feel natural.


Template Literals with HTML

They are commonly used to build HTML snippets dynamically.


let card = `
  

JavaScript Course

Learn modern JavaScript step by step

`;

This pattern is widely used in real-world applications.


Common Beginner Mistakes

  • Using quotes instead of backticks
  • Forgetting ${} around variables
  • Overusing template literals for simple strings

Use template literals when they improve clarity.


Thumb Rules

  • Use backticks (`) for template literals
  • Use ${} to embed variables or expressions
  • Prefer template literals for dynamic strings
  • Keep strings readable and clean

What Comes Next?

Now that strings are easier to handle, the next step is working with multiple values efficiently.

In the next lesson, we will learn about spread and rest operators.