Open In App

JavaScript | template literals

Template Literal in ES6 provides new features to create a string that gives more control over dynamic strings. Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literal is created using the backtick (`) character.

Syntax:



var s=`some string`;

Multiline Strings: In-order to create a multiline string an escape sequence \n was used to give new line character. However, Template Literals there is no need to add \n string ends only when it gets backtick (`) character.

Expressions: To dynamically add values into new Template Literals expressions are used. The ${} syntax allows an expression in it that produces the value. This value can be a string stored in a variable or a computation operation.



${expression}

Tagged Templates: One of the features of Template Literals is its ability to create Tagged Template Literals. Tagged Literal is written like a function definition, but the difference is when this literal is called. There is no parenthesis() to a literal call. An array of Strings are passed as a parameter to a literal.

Raw String: Raw method of template literal allows access of raw strings as they were entered, without processing escape sequences. In addition, the String.raw() method exists to create raw strings just like the default template function, and string concatenation would create.

Nested Templates: Templates can be nested if it contains multiple expression evaluation or multiple condition checking. Instead of using else if ladder this is readable and gives ease to the developer. The code below finds the maximum of three numbers using conditional operator and nested template literal.


Article Tags :