Template Literals in JavaScript

Video Tutorial
FREE
Template Literal and multi-line strings thumbnail
This video belongs to
JavaScript Course With Certification: Unlocking the Power of JavaScript
9 modules
Certificate
Topics Covered

Template literals and string literals in Javascript serve as methods for defining strings. String literals, formed with single (') or double (") quotes, lack the ability to create multiline strings without concatenation or escape characters and do not support expression interpolation. On the other hand, template literals, enclosed within backticks (``), offer enhanced functionality. They support multiline strings without the need for concatenation or escape characters, and they enable expression interpolation using ${}, making them more versatile and readable in modern JavaScript development.

Syntax of Template Literals in Javascript

The untagged template literals are simply declared by using backticks (``). The untagged template literals would simply return a string.

The ${ variable } is used to place placeholders in template literals. The variable inside the braces is the placeholder, and it can be the value of any data type.

The func before the template literal in a tagged template literal is tagged template. It is generally a function that gets called when we declare the tagged template literals, with the template literal as an argument.

Parameters of Template Literals in JavaScript

Template Literals in JavaScript are defined using back-ticks (``) and come with three essential parameters: string text, expression, and tagFunction.

  1. String Text:

The string text parameter captures the static portions of the template literal, providing a foundation for constructing the string. It encompasses the unchanged elements within the backticks.

  1. Expression:

Denoted by ${...}, the expression parameter facilitates dynamic content inclusion. Variables or expressions within this parameter allow developers to incorporate changing values into the resulting string.

  1. Tag Function:

The tagFunction parameter involves a custom function (or tag) that processes the entire template literal. This advanced feature enables developers to manipulate the resulting string according to specific requirements, offering enhanced control.

Understanding and utilizing these parameters collectively contribute to the versatility and expressive power of template literals in JavaScript.

Description of Template Literals in JavaScript

Template literals are ES6 addition to Javascript that allows users to embed expressions. These expressions can be a number or a string or a variable or constant of any data type in Javascript.

The template literals are declared by using backticks (``). By default, the template literals concatenate its parts into a string. These strings are also known as dynamic strings, as they could include variables placeholders whose values can be changed.

The placeholder in template literals are declared by ${}. The placeholder can be placed inside the braces, and it can be a constant or a variable or an arithmetic expression, etc.

The template literals in Javascript support multiple features like multiline strings, nesting, expression interpolation etc.

The template literals in Javascript are mainly of two types:

Untagged template literals:

The untagged template literals javascript concatenates the whole expression and returns a string. It simplifies string interpolation (for e.g. before the introduction of template literals, in order to place a numeric value in between a string, we have to divide the string into two parts and then concatenate the strings and the numeric values using the + operator, whereas in untagged template literals we can simply insert variables and expression using ${}).

Tagged template literals:

The tagged template literals allow us to call the tagged template as a function.

We have discussed the tagged template literals javascript in much detail with examples in the below section.

Multiline Strings

It's a common practice to write text pieces in multiple lines. In the traditional strings (which is declared by using '' or "" in javascript), this could be achieved by using \n.

For Example

In the above example, the compiler, while logging through the string before the + operator encounters the \n, thus it changes the line before printing the string after the + operator.

The above result can be achieved by the untagged template literals without adding any \n. We can change the line of the string output by simply changing the line of the string inside the (``) during string declaration.

Example:

In the above example, we can see that the line of the string output has changed when we have changed the line of string inside the backticks (``) in the declaration. This is the multiline string property of template literals javascript.

String and Expression Interpolation

The template literals Javascript support string and expression interpolation, i.e. we can embed placeholders or expressions in between the string.

In traditional strings, to include an expression, use the + operator for concatenation. For eg,

In the above example, the variables name, mathScore, scienceScore are concatenated with the strings to produce the output.

The above result can be obtained by using ${} inside the template literals. We can place the variables or expressions inside the braces and it will substitute the variables and expressions with their values.

Example:

In the above example, the variables- name, mathScore and scienceScore and the expression mathScore + scienceScore are substituted by their respective values.

Nesting Templates

Nesting templates mean including a new template literal within a template literal. Template literals in javascript allow the nesting of templates, i.e., we can declare a new template literal inside a template literal.

Nesting templates come in handy in situations where there is multiple condition checking. It can be used to nest conditional operators.

Templates are nested by declaring backticks strings inside a template by using ${}.

Example:

In the above example, the first inputs are a = 1, b = 2, c = 3, now the (b<a && b<c) expression will be return false as b > a, thus the conditional operator will return ${(a<c) ? a:c}. since a < c so the second operator will return a. The the final result will be min value is a. Here we can see that the program first iterates through the outer template, since the (b<a && b<c) condition returns a new template so it goes inside that template and appends it's output to the final result.

In the second case, the input are a = 2, b = 1, c = 3. Now the (b<a && b<c) expression will be return true as b < a and b < c. Thus the conditional operator will return the inner template literal b, which will get appended to the reslting string.

In the third case, the inputs are a = 2, b = 3, c = 1, now the (b<a && b<c) expression will be return false as b > a and b > c, thus the conditional operator will return ${(a<c) ? a:c}. since a > c so the second operator will return c. The the final result will be min value is c. Here we can see that the program first iterates through the outer template, since the (b<a && b<c) condition returns a new template so it goes inside that template and appends it's output to the final result.

Tagged Templates

The tagged templates can be used it parse template literals with a function. The tagged template before the string calls the function, and the string values are passed to the function as an array of arguments. If there are substitutions in the string, then these substitutions are passed as the next arguments.

Example:

In the above example, the func is a tagged function, which is called with the template literal namehasscored{name} has scored {mathScore} in maths and ${scienceScore} in Science. Thus his total score is =.

The func function gets called with four arguements: str, userName ,mathS, scienceS

The str is an array of string elements that is in the literal. // ['has scored ', 'in maths and ', 'in Science. Thus his total score is = ']

The userName does takes the value of ${name} Similarly mathS and scienceS will take the values of mathScore and scienceScore respectively.

The str elements are accessed through their indexed and stored in s1, s2, s3.

The function adds these score and stores into a variable totalScore and then returns the expression.

userName{userName}{s1}mathS{mathS}{s2}scienceS{scienceS}{s3}totalScore{totalScore}

Where the values if placeholders are substituted.

Raw Strings

We've already seen how \n can be used to change the line of a string. Similarly, we can use other escape sequences to skip lines, spaces, etc.

The raw is a property of the first argument of the tagged template that allows us to access the string in the exact same way they were entered (i.e. the escape sequences like \n, \t are also simply considered as a string).

Example:

In the above example, as we all know in template literals javascript, the first argument of the tagged template in template literals javascript is the array of string values that are passed, the str is an array with This is an example of:\n Raw strings as its value.

Now, the str[0], will output the string value. While printing the string, it encounters \n thus, it changes the line and prints the rest of the string.

Similarly, the str.raw[0], will output the string value. While printing the string it encounters the \n as well, but due to the raw property, it considers the \n as a string only, thus it doesn’t change the line, prints \n and keeps printing the string.

Tagged Templates and Escape Sequences

The ES2016 behavior:

According to ECMAScript 2016, the tagged templates in template literals javascript are bound to follow the mentioned rules for escape sequences:

  • The Unicode escapes should start with "\u".
  • The Unicode code point escapes should be indicated by "\u{}".
  • The Hexadecimal escapes should start by "\x".
  • The Octal literal escapes should start by "\0o" and should be suffixed by one or more than one digit.

ES2018 revision of illegal escape sequences

In 2018, the provisions were revised in template literals javascript. It was proposed that Template literals should allow the embedding of languages. This revision removed the syntax restriction of `ECMAScript escape sequences.

Browser Compatibility

BrowserTemplate literalEscape sequences allowed in tagged template literals
Chrome4162
Safari911
Opera2849
Firefox3453
Edge1279
Internet ExplorerN/AN/A
  • If the row contains a number (for example, 1 for Firefox), it indicates that the browser version specified is the bare minimum required to support the tag in template literals javascript.

  • N/A means the browser doesn't support the feature.

Conclusion

  • Template literals in javascript can be used to write complex strings without doing any concatenation, etc.
  • We can add placeholders in the template literals using ${}. This placeholder can have a constant or a variable, or an expression.
  • Template literals are of two types: tagged template literals and untagged template literals.
  • The untagged template literals in the template literals javascript return a string that may contain substitution values.
  • The tagged template literals in the template literals javascript call the tagged template as a function with the array of strings as its the first argument, followed by the substitutions(if any) as the function's next arguments.
  • The return value of tagged template literals needs not to be a string, it can be anything the tagged template returns.
  • The template literals support multiline strings, expression interpolation, raw strings, and nesting templates.