JavaScript Template Literals

Fatemeh Paghar - Mar 21 - - Dev Community

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`;
console.log(escaped);
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.

References:
Template literals (Template strings)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .