Template literals in JavaScript

Tagged templates ( function calling using template literals)

Vrushabh Bayas
3 min readMar 24, 2021

Template literal is one of the feature of JavaScript which was released in the ES6. Today we are going to talk about it.

So template literal is used for concatenating the strings and we can also call any function using template literals that is called as tagged templates. We will see that with example in the end of this post so just read don’t skip it.

In old syntax we used to add the strings using the plus (+) operator as shown in the code snippet.
Using template literal there is no need to use the plus (+) operator.

Template literals are enclosed by the (``) back-ticks character instead of the single or double quote. Template literals can contain place holders. These are indicated by the dollar sign ($) and curly braces (${expression}).

Multi-line string

Using template literal we can split our string into multiple lines. Any new line character inserted into the source string is part of the template literal.

Using normal syntax you would have to use following syntax to get the multi-line string.

Using template literal you can do the same like this

Tagged templates ( function calling using template literals)

Yes you read it right we can call the function using the template literals.lets see the below example.

More advanced form of the template literals are tagged templates.If we call the function using template literal then the first argument of the tagged function contains an array of string values and remaining arguments contains expressions we can catch them into array suing rest operator.

To simplify it lets see below example in which we are adding two numbers. We have written addTwoNum function and invoking that function with the help of the template literals.

As you can see in first argument of the function is literals which includes all the strings.In second argument we are using rest operator to catch all the expressions in to an array.

This example is just for demo purpose it’s not the actual use of tagged template literals.

Thank you for reading guys.I hope you liked it if yes then don’t forget to give a clap that will motivate me.

--

--

Vrushabh Bayas

Software engineeer @joshSoftware Pvt Ltd. love to explore new things and teach them to as many people as possible.