Many times we will dynamically generate some text using variables. We have done this in previous lessons using string concatenation. Let's see one more example:
let name = "Andy";
let pet = "dog";
let breed = "poodle";
let message = "Hey, " + name + "! Nice " + pet + "! Is it a " + breed + "?";
console.log(message); // Output: Hey, Andy! Nice dog! Is it a poodle?
While this approach perfectly works, it's not ideal. You can see that as our text gets more complicated, it's harder for the reader to visualize all the concatenations in their head.
This can be achieved much easier with string interpolation.
String Interpolation:
String interpolation is a process substituting values of variables into placeholders in a string. For instance, if you have a template for saying hello to a person like:
Hello {name}, nice to meet you!
you would like to replace the placeholder for name of person with an actual name. This process is called string interpolation.
Template literals:
The string interpolation in TypeScript is performed by template literals (strings wrapped in backticks ``) and ${expression} as a placeholder:
let name = "Mike";
let message = `Hello ${name}, nice to meet you!`;
console.log(message); // Output: Hello Mike, nice to meet you!
With these ${}, we're defining place holders or holes in our string, and when we run our program these holes will be filled with the value of our variables.
So here we have one place holder or one hole in our string and it is for the value of the name variable.
We can have as many place holders as needed:
let name = "Mike";
let pet = "cat";
let breed = "ragdoll";
let message = `Hey, ${name}! Nice ${pet}! Is it a ${breed}?`;
console.log(message); // Output: Hey, Mike! Nice cat! Is it a ragdoll?
Assignment
Follow the Coding Tutorial and let's practice with string interpolation!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
