DEV Community

Cover image for JavaScript Template Literals
Fatemeh Paghar
Fatemeh Paghar

Posted on • Updated on

JavaScript Template Literals

Template literals, introduced in ECMAScript 6 (ES6), are a way to work with strings more efficiently and expressively in JavaScript.

  • Syntax: Template literals are enclosed in backticks. For example:
const name = 'John';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!
Enter fullscreen mode Exit fullscreen mode
  • Expression Interpolation: You can embed expressions within template literals using ${}:
const a = 5;
const b = 10;
const sum = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(sum); // Output: The sum of 5 and 10 is 15.
Enter fullscreen mode Exit fullscreen mode
  • Function Interpolation: You can also embed function calls within template literals:
function capitalize(str) {
    return str.toUpperCase();
const text = `This is ${capitalize('important')}.`;
console.log(text); // Output: This is IMPORTANT.
Enter fullscreen mode Exit fullscreen mode
  • Nested Templates: You can nest template literals within each other:
const firstName = 'John';
const lastName = 'Doe';

function fullName(fName, lName) {
  return fName + " " + lName;

console.log(`FirstName = ${firstName} and lastname = ${lastName} and fullname = ${fullName(`${firstName}`,`${lastName}`)}`)
Enter fullscreen mode Exit fullscreen mode
  • Tagged Templates: Template literals can be tagged with a function, which allows you to modify the output using the tagged function. This is an advanced feature that enables powerful string manipulation and templating:
function tag(strings, ...values) {
    return strings.reduce((result, str, i) => {
        result += str;
        if (i < values.length) {
            result += values[i];
        return result;
    }, '');
const a = 10;
const b = 5;
const result = tag`The result of ${a} + ${b} is ${a + b}.`;
console.log(result); // Output: The result of 10 + 5 is 15.
Enter fullscreen mode Exit fullscreen mode
  • Escape Sequences: Template literals still support escape sequences like \n, \t, etc., just like regular strings:
const escaped = `This is a string\nwith a new line`;
Enter fullscreen mode Exit fullscreen mode

These points demonstrate the flexibility and power of template literals in JavaScript, making string manipulation and interpolation more intuitive and expressive.

In conclusion, template literals in JavaScript provide a versatile and expressive way to work with strings. With their ability to embed variables, expressions, and even nested templates directly within strings, they offer a more readable and concise syntax compared to traditional string concatenation methods. Additionally, tagged template literals introduce advanced capabilities by allowing custom processing of string segments and interpolated values. Whether it's simple string interpolation or complex string manipulation tasks like syntax highlighting or internationalization, template literals offer a powerful tool for developers to create dynamic and flexible string content in their JavaScript applications.

Template literals (Template strings)

Top comments (2)

joeglombek profile image
Joe Glombek

Hi Fatemeh, thanks for the article! I just had a couple of comments.

I was a little confused by your tagged function example - is it doing exactly the default behaviour for template literals is? I've not seen this functionality before, so breaking down the example further (or providing an example that isn't the default behaviour) would be hugely appreciated!

Secondly, my understanding of nested templates is a little different to the example you provide - your example seems to just be passing a template literal into another function as a string (or am I missing something here, is it not passed as a string and does this provide performance benefits I'm not seeing?)

The MDN article you link to lists something I'd more readily associate with "nesting":

const classes = `header ${
  isLargeScreen() ? "" : `icon-${item.isCollapsed ? "expander" : "collapser"}`

Enter fullscreen mode Exit fullscreen mode

Here the second template literal is actually inside the first.

Again, thanks for the article - template literals aren't something I've investigated beyond the basic usage so far, so thanks! Just wanted to clarify these two points.


fpaghar profile image
Fatemeh Paghar

You are right, In my example, the behavior is like default.

Tagged templates are like upgraded versions of template literals. They let you use a function to handle the template, rather than just seeing it as a simple string. This gives you more say over how the strings and expressions inside are put together. To use a tagged template, you write it a bit like calling a function with something in parentheses. But instead of using regular parentheses, you use a template literal. The function you use to handle the template is called a "tag function".

Understanding the difference between template literals and tagged templates is key:
Template literals work by turning into a string, with expressions put right into the string.
Tagged templates work differently. They send both the literal strings and the results of the expressions to a function. This function can then change and give them back in a unique way.
Tagged templates provide more freedom and control over how strings are made, making them strong tools for tricky string handling.

function formatDate(strings, ...values) {
  const outputArray =
    (value, index) =>
      `${strings[index]}${value instanceof Date ? value.toLocaleDateString() : value}`,
  return outputArray.join("") + strings[strings.length - 1];

//Using tagged template
const myDate = new Date();
console.log(formatDate`Today's date is ${myDate}.`); // Today's date is 12/06/2023.

// default
const myDate1 = new Date();
console.log(`Today's date is ${myDate1}.`); // Today's date is Wed Mar 27 2024 17:58:59 GMT+0100 (Central European Standard Time).
Enter fullscreen mode Exit fullscreen mode