Inthis article, I will discuss another powerful feature of modern JavaScript; template literals, which was released in the 2015 edition of the ECMAScript specification and was referred to as template strings prior to ES6. Similar to string interpolation features in other languages like Ruby and Phyton, template literals provide syntactic sugar that allows us to construct strings more quickly. Before template literals were added to the JavaScript language in ES6, single quotes (‘ ’) and double quotes (“ ”) were the only ways to make a string. Template literals offer another way to declare strings that makes use of backtick ( ) character.

Let’s now look at the template literals in detail.


1. Basic Syntax:

Template literals use enclosing backticks (``) instead of using single (‘ ’) or double (“ ”) quotes as shown in the following example:

Template literals use backticks ( ) instead of single or double quotes to declare strings

Using the backticks allows us to use the single or double quotes in the template literal without escaping because each type of character only needs to escape its own type. So, in template literals, we only need to escape backticks by using a backslash( \ ).

Template literals do not need to escape single or double quotes

We have seen examples of how to create strings with single quotes, double quotes, and backticks. Now we will see more examples showing the advantages of using template literals.

#javascript #string #es6 #template-literals #programming

JavaScript: Template Literals (ES6)
1.75 GEEK