Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript: A Better Way to Work with Strings

Updated
8 min readView as Markdown

If you have been writing JavaScript for a while, you have almost certainly run into situations where building a string felt unnecessarily messy. You are juggling quotes, plus signs, and variables, squinting at the screen trying to figure out why there is a missing space or a broken line. Template literals were introduced in ES6 to fix exactly this, and once you start using them, going back to the old way feels genuinely painful.

Let's look at what they are, why they exist, and how to use them well.


The problem with string concatenation

Before template literals, the only way to embed a variable inside a string was through concatenation, using the + operator to stitch pieces together.

var playerName = "Virat Kohli";
var score = 94;
var message = "Player: " + playerName + " scored " + score + " runs today.";
console.log(message);
// Player: Virat Kohli scored 94 runs today.

For a short string, this is manageable. But things get worse quickly.

var city = "Mumbai";
var team = "India";
var opponent = "Australia";
var venue = "Wankhede Stadium";

var announcement =
  "The match between " + team + " and " + opponent +
  " will be held in " + city + " at " + venue + "." +
  " Get your tickets now!";

By the time you reach the end of that string, you have lost track of what the string even says. Every variable insertion requires you to close the string, add a +, write the variable, add another +, and reopen the string. It is repetitive and error prone.

Multi-line strings were even worse. JavaScript does not let you simply break a string across lines with regular quotes. The old workaround was to concatenate each line with a \n escape or a newline character:

var profile =
  "Name: Deepika Padukone\n" +
  "Profession: Actor\n" +
  "Based in: Mumbai";

console.log(profile);

There is nothing technically wrong with this, but it is noisy. You are spending mental energy on the syntax rather than the content of the string.


Introducing template literals

Template literals use backticks ` instead of single or double quotes. That is the only syntax change you need to know to get started.

var greeting = `Hello, world!`;
console.log(greeting); // Hello, world!

At face value, this looks the same as using regular quotes. The difference shows up the moment you need to embed a variable or write across multiple lines.


Embedding variables with ${}

To insert a variable (or any expression) into a template literal, you wrap it in ${}. This is called string interpolation.

var playerName = "Virat Kohli";
var score = 94;

var message = `Player: \({playerName} scored \){score} runs today.`;
console.log(message);
// Player: Virat Kohli scored 94 runs today.

Compare this directly to the concatenation version from earlier. The content of the string is readable as a sentence. You are not context-switching between string segments and variables. You see the whole thing at once.

Here is the multi-variable example again, rewritten with template literals:

var city = "Mumbai";
var team = "India";
var opponent = "Australia";
var venue = "Wankhede Stadium";

var announcement = `The match between \({team} and \){opponent} will be held in \({city} at \){venue}. Get your tickets now!`;

Same result, far less noise.


You can put any expression inside ${}

The ${} slot is not limited to variables. You can put any valid JavaScript expression inside it: arithmetic, function calls, ternary operators, method calls, anything that evaluates to a value.

var a = 10;
var b = 3;

console.log(`Sum: ${a + b}`);        // Sum: 13
console.log(`Product: ${a * b}`);    // Product: 30
console.log(`Power: ${a ** b}`);     // Power: 1000

Function calls work too:

function getCity() {
  return "Bangalore";
}

var name = "Anil Kapoor";
console.log(`\({name} is currently in \){getCity()}.`);
// Anil Kapoor is currently in Bangalore.

And ternary expressions, which are useful for conditional strings:

var score = 85;
var result = `The player ${score >= 50 ? "passed" : "failed"} the fitness test.`;
console.log(result);
// The player passed the fitness test.

Multi-line strings

This is where template literals save you a lot of annoyance. With backticks, you can simply press Enter inside the string, and the newline is included automatically. No \n, no concatenation.

var profile = `Name: Deepika Padukone
Profession: Actor
Based in: Mumbai`;

console.log(profile);
// Name: Deepika Padukone
// Profession: Actor
// Based in: Mumbai

This becomes especially useful when you are building structured content, like an HTML snippet or a formatted message:

var player = "MS Dhoni";
var matches = 350;
var average = 51.3;

var card = `
Player Profile
--------------
Name    : ${player}
Matches : ${matches}
Average : ${average}
`;

console.log(card);

Output:

Player Profile
--------------
Name    : MS Dhoni
Matches : 350
Average : 51.3

Try doing this with concatenation and you will immediately appreciate what template literals save you.


Real-world use cases

Template literals are not just a convenience for small examples. Here are situations where they genuinely clean up real code.

Building dynamic messages

function getWelcomeMessage(name, city) {
  return `Welcome back, \({name}! You are logged in from \){city}.`;
}

console.log(getWelcomeMessage("Ranveer Singh", "Delhi"));
// Welcome back, Ranveer Singh! You are logged in from Delhi.

Generating HTML strings

When you need to build an HTML fragment in JavaScript (which happens often in DOM manipulation or email templating), template literals make the structure easy to follow:

var movie = {
  title: "Pathaan",
  year: 2023,
  rating: 8.1
};

var card = `
  <div class="movie-card">
    <h2>${movie.title}</h2>
    <p>Year: ${movie.year}</p>
    <p>Rating: ${movie.rating}/10</p>
  </div>
`;

document.body.innerHTML = card;

Compare this to building the same HTML with concatenation and you will see how much more readable the template version is.

Constructing URL paths

var baseUrl = "https://api.cricketboard.in";
var endpoint = "players";
var playerId = 42;

var url = `\({baseUrl}/\){endpoint}/${playerId}/stats`;
console.log(url);
// https://api.cricketboard.in/players/42/stats

Logging and debugging

Template literals make debugging messages much easier to write and read:

var user = { name: "Alia Bhatt", age: 30, city: "Mumbai" };

console.log(`User: \({user.name} | Age: \){user.age} | City: ${user.city}`);
// User: Alia Bhatt | Age: 30 | City: Mumbai

A note on nesting

You can nest template literals inside one another, though it is worth using this sparingly. It is powerful, but it can get confusing if overdone:

var players = ["Rohit Sharma", "KL Rahul", "Virat Kohli"];

var list = `Top batters: \({players.map(p => `\){p}`).join(", ")}`;
console.log(list);
// Top batters: Rohit Sharma, KL Rahul, Virat Kohli

This works cleanly because each nested template is short. If you find yourself three levels deep, that is usually a sign to extract part of the logic into a variable or function first.


What to watch out for

Template literals are straightforward, but there are a couple of things worth knowing before you go all in.

First, be careful about whitespace in multi-line templates. JavaScript captures every character inside the backticks exactly as written, including indentation. If your template literal is inside a function and you indent it for readability, that indentation will show up in the output.

function getCard(name) {
  return `
    Name: ${name}
    Welcome!
  `;
}

console.log(getCard("Priyanka Chopra"));
// (the output will have leading spaces on each line)

This usually does not matter for HTML rendering since browsers collapse whitespace, but it can be surprising in plain text output or when working with APIs that parse line content exactly.

Second, backticks themselves need to be escaped if you need one inside a template literal. Use a backslash: \`.

var code = `Use backticks like \`this\` in Markdown.`;
console.log(code);
// Use backticks like `this` in Markdown.

Wrapping up

Template literals are one of those ES6 additions that, once you have used them, you will find hard to live without. They do not change how JavaScript works at a fundamental level, but they make day-to-day string handling significantly more readable and maintainable.

The core of it is simple: backticks instead of quotes, ${} for embedding expressions, and line breaks that just work. Most of the improvements are about readability, which matters more than people often give it credit for, especially on large codebases or when you are reading code you did not write.

If you have been using concatenation out of habit, this is a good time to switch. The difference shows up immediately.

More from this blog