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:
1 |
`a text string ${JavaScript code like variable, function etc can be here} another text string`; |
- 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.
1 2 3 |
let myName = "Sara"; let myAge = 40; console.log(`<code>Hello, my name is ${myName} and I am ${myAge} years old.</code>`); |
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.