JavaScript Template Literals


In ES6, Template Literal introduces additional string-creation tools that offer you more control over dynamic strings. String is traditionally generated with single quotes (') or double quotes (") quotations. The backtick (') character is used to build template literals.

Syntax

Example

Preview

Multiline Strings

To construct a multiline string, the escape sequence n was employed to provide a new line character. However, there is no need to include n string ends only when it encounters a backtick (') character in Template Literals.

Example

Preview

Expressions

Literals expressions are used to dynamically add values to new Templates. The $ syntax supports an expression that yields the value. This value can be a variable-stored string or a calculation procedure.

Example

Preview

Tagged Templates

One of Template Literals' characteristics is the ability to construct Tagged Template Literals. The distinction between Tagged Literal and a function definition is when this literal is invoked. A literal call has no parentheses(). A literal is handed an array of Strings as an argument.

Example

Preview

Raw String

The raw method of template literal allows you to access raw strings as they were typed, without having to process escape sequences. Furthermore, the String.raw() method exists to generate raw strings in the same way as the default template function and string concatenation would.

Example

Preview

Nested Templates

If a template has numerous expression evaluations or multiple condition checks, it can be nested. Instead of using a ladder, this is more understandable and makes the developer's life easier. The code below uses a conditional operator and a nested template literal to find the maximum of three numbers.

Example

Preview