Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Updated
•7 min read•View as Markdown
Template Literals in JavaScript
S

I am MERN STACK Web Developer.I am Student of BCA.

JavaScript has come a long way in making string handling easier and more intuitive for developers. One of the most exciting and practical additions to the language is Template Literals. Introduced in ECMAScript 6 (ES6), template literals are more than just a new way to define strings—they are a powerful tool for string interpolation, embedding expressions, multi-line strings, and more.

In this article, we’ll dive deep into template literals and explore their various capabilities, providing examples and discussing how they can simplify your code. Whether you're a beginner or an experienced JavaScript developer, understanding template literals will help you write cleaner and more efficient code.

What Are Template Literals?

Template literals are a way of writing strings in JavaScript, but with extra features that allow for easy interpolation, multi-line strings, and the inclusion of expressions directly within the string.

Before ES6, developers had to rely on concatenation using the + operator to insert variables or expressions into strings. This approach could quickly become cumbersome and error-prone when dealing with complex or multi-line strings.

Here’s an example of how string interpolation was typically done before template literals:

let name = "Suraj";
let age = 20;
let greeting = "Hello, my name is " + name + " and I am " + age + " years old.";
console.log(greeting);

This method of concatenating strings with variables is verbose and can become unwieldy when dealing with more complex strings. Template literals offer a cleaner solution:

let name = "Suraj";
let age = 20;
let greeting = `Hello, my name is \({name} and I am \){age} years old.`;
console.log(greeting);

With template literals, we no longer need to worry about breaking up the string with + operators or managing spaces and formatting. Let’s explore this feature further.

Syntax of Template Literals:

Template literals are defined using backticks (`), as opposed to single (') or double (") quotation marks.

let simpleString = `This is a template literal.`;

Within template literals, you can embed any JavaScript expression using the ${} syntax. These expressions are automatically evaluated, and the result is inserted into the string.

String Interpolation

The most common use of template literals is string interpolation—the ability to embed variables and expressions directly inside a string.

let item = "macbook";
let price = 99999;
let message = `The price of the ${item} is $${price}.`;
console.log(message);

In this example, \({item} and \){price} are placeholders that get replaced with the values of the item and price variables. You can also embed more complex expressions inside the placeholders:

let num1 = 10;
let num2 = 20;
let result = `The sum of \({num1} and \){num2} is ${num1 + num2}.`;
console.log(result); // The sum of 10 and 20 is 30.

In this case, ${num1 + num2} evaluates the expression and inserts the result into the string.

Multi-line Strings

Before template literals, writing multi-line strings in JavaScript required using awkward concatenation or escape characters (\n for a new line).

let multiLine = "This is line one.\nThis is line two.";
console.log(multiLine);

With template literals, multi-line strings are much simpler and more readable. You can just press Enter where you want the line break:

let multiLine = `This is line one.
This is line two.`;
console.log(multiLine);

This feature makes template literals especially useful when working with formatted text, HTML, or SQL queries.

Embedding Expressions

Beyond simple variables, template literals can embed any JavaScript expression, including function calls, ternary operators, and more:

let name = "Bob";
let isAdmin = false;
let role = `User role: ${isAdmin ? 'Admin' : 'Guest'}`;
console.log(role); // User role: Guest

In this example, a ternary operator inside the template literal determines whether to display “Admin” or “Guest” based on the isAdmin boolean.

You can even call functions directly inside the template literal:

function greet() {
 return "Hello, world!";
}
let message = `The greeting is: ${greet()}`;
console.log(message); // The greeting is: Hello, world!

Template literals make it easy to dynamically generate content based on complex logic or external data.

Tagged Template Literals

A less commonly known feature of template literals is tagged template literals. Tags are essentially functions that process the template literal and allow for advanced manipulation of the string.

The syntax involves placing a function name before the template literal. The function will receive the string parts and the interpolated values as arguments.

function tag(strings, ...values) {
 console.log(strings); // ['The price of ', ' is ', '.']
 console.log(values); // [999, 'laptop']
}
let price = 999;
let item = 'laptop';
tag`The price of \({price} is \){item}.`;

In this example, the tag function receives two arguments: an array of string literals and an array of the interpolated values (999 and 'laptop'). This can be useful for advanced string formatting, localization, or even custom templating engines.

Raw Strings with String.raw

JavaScript also provides a built-in tag function called String.raw, which allows you to access the raw content of a template literal, including escape characters.

let path = String.raw`C:\Development\project\file.txt`;
console.log(path); // C:\Development\project\file.txt

Here, String.raw prevents the backslashes from being treated as escape characters, preserving the raw string. This can be useful when dealing with file paths, regular expressions, or any other strings that require precise formatting.

Performance Considerations

While template literals make code cleaner and more readable, there are some performance considerations to keep in mind.

String Concatenation: When you use template literals with multiple expressions or complex logic, JavaScript evaluates the expressions each time the literal is constructed. In performance-critical applications (such as rendering loops in UI frameworks), this can introduce overhead compared to pre-computed string concatenation.

Tagged Templates: Since tagged template literals involve invoking a function, they are inherently slower than simple string interpolation. However, the impact is usually negligible unless you’re processing large amounts of data or using them in performance-critical code.

For most use cases, the improved readability and maintainability of template literals far outweigh any potential performance concerns.

Best Practices for Using Template Literals

Here are some best practices to keep in mind when using template literals in your projects:

  1. Use for readability: Template literals should make your code more readable and easier to maintain. Use them to simplify string interpolation and multi-line strings instead of cluttering your code with + operators.

  2. Avoid excessive logic inside templates: While you can embed any JavaScript expression inside a template literal, try to keep the logic simple. If an expression is too complex, consider moving it outside the template literal for better readability.

  3. Use tagged templates for specialized formatting: If you need to perform custom formatting (e.g., localization, currency, or escaping), tagged template literals are a powerful tool. Just remember that they come with some performance overhead.

  4. Leverage multi-line support: Template literals are excellent for working with multi-line strings, such as HTML or formatted text. This can make your templates much cleaner and easier to understand.

  5. Test for performance bottlenecks: In cases where performance is critical, such as in tight loops, you may want to test the impact of using template literals vs. concatenation. Most of the time, template literals are performant enough, but in edge cases, direct concatenation might be faster.

Conclusion

Template literals are a versatile and powerful feature in JavaScript that simplifies string handling in many scenarios. Whether you’re dealing with string interpolation, multi-line strings, or even custom formatting through tagged templates, template literals provide a cleaner, more intuitive way to write and manage strings.

By understanding and applying template literals effectively, you can improve the readability, maintainability, and flexibility of your JavaScript code. They represent one of the many modern JavaScript features that empower developers to write more expressive and concise code.