JavaScript Template Strings

Template strings provides a method of combining two different type of data (for example string and variable) in JavaScript without using concatenation. For example when we want to place a variable inside a string, we can use template strings or template literals. This method is called Interpolation.

Syntax for template strings:

  • Back-ticks are used instead of double or single quotes.
  • Dollar sign and curly brackets ${} is a place holder, we can put any variable, function or operators etc inside the place holder.

Example of JavaScript Template Strings:

We can combine text with variables using concatenation operator. The ${} is used for Interpolation.

In the above example we have created two variables myName and myAge. We are interpolating / concatenating text strings like Hello, my name is with the variable myName and variable myAge. This way of putting variables into string exist in many programming languages. However in JavaScript before ES6, we had to use the concatenation operator + when we wanted to put variables inside a string. Using Templates Strings the code is more readable and faster than concatenation.