Template Literals in JavaScript

Template literals, also known as template strings, are a new feature introduced in ECMAScript 6 that allows for easy and efficient string interpolation in JavaScript. They provide a way to embed expressions into a string and make it easier to write complex string manipulations. In this article, we will explore the basics of template literals and provide some examples of how they can be used.

Basic Syntax

Template literals are enclosed in backticks () instead of single or double quotes. They allow for the embedding of expressions by enclosing them in ${}. Here’s a basic example:

Output:

In this example, we define a variable name with the value “John” and use it to create a message string that includes the value of name. We then log the message to the console.

Multi-line Strings

Template literals also make it easier to create multi-line strings. In traditional JavaScript, multi-line strings required the use of the \n escape character. With template literals, multi-line strings can be created by simply pressing enter:

Output:

In this example, we define a message string that spans multiple lines. We simply press enter to create new lines, without the need for escape characters.

Expression Interpolation

Template literals can also be used to embed expressions inside strings. Here’s an example:

Output:

In this example, we define two variables num1 and num2 with the values 10 and 20 respectively. We then use these variables to create a result string that includes an expression that adds the values of num1 and num2. The expression is enclosed in ${}.

Tagged Templates

Tagged templates are another feature of template literals that allow you to process template literals with a function. Here’s an example:

Output:

In this example, we define a function processMessage that takes the strings and values of a template literal as arguments. We then use the function to process a template literal that includes a variable name. When the processMessage function is called, it outputs the strings and values that were passed to it.

Conclusion

In this article, we have explored the basics of template literals in JavaScript. We have seen how they can be used to create multi-line strings, embed expressions, and process template literals with a function. Template literals are a powerful feature that can make string manipulation in JavaScript much easier and more efficient.

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *