DEV Community

Hiral
Hiral

Posted on

Template Literals in JavaScript

when you first start javascript building string often involves using the + operator.While this works quickly but it become messy and hard to read as code grows.
Before ES6, developers created strings like this:


let name = "Alice";
let age = 25;

let message = "Hello, my name is " + name + " and I am " + age + " years old."
Enter fullscreen mode Exit fullscreen mode

This approach has several drawbacks:

  • Hard to read: The sentence is broken into multiple parts.
  • Error-prone: Easy to forget spaces or quotes.
  • Messy with complex strings: Adding more variables makes it worse.
  • Difficult for multi-line strings: Requires \n or awkward formatting. Template Literal Syntax

Template literals were introduced in ES6 and use backticks (`) instead of quotes.

javascript
let message =
Hello, my name is Alice.;

Embedding Variables in Strings

Instead of breaking the string with +, you can directly insert variables using ${}:

`javascript
let name = "Alice";
let age = 25;

let message = Hello, my name is ${name} and I am ${age} years old.;
`

  • Cleaner and easier to read
  • Looks more like natural language
  • No need to worry about spacing issues Multi-line Strings Made Easy: With traditional concatenation:

javascript
let text = "This is line one.\n" +
"This is line two.\n" +
"This is line three.";

With template literals:

javascript
let text =
This is line one.
This is line two.
This is line three.;

Some Use cases

  • Creating API URLs

javascript
let userId = 42;
let url =
https://api.example.com/users/${userId}`;
`

  • Generating HTML templates


let html = <div class="user">${name}</div>;

Logging and debugging

javascript
console.log(
User ${name} logged in at ${time});
plaintext

`

Top comments (0)