A template string is a regular JavaScript string which is enclosed with back-tick characters (`
) seeded with placeholders denoted with ${ }
. At runtime, your code replaces the placeholders with real values.
Template String Example
Let’s see a very basic example of template string. In this example, at runtime, the code replaces placeholders with the actual values of variables. It’s called variable substitution.
const name: String = 'Lokesh'; const age: number = 35; let message: string = `My name is ${ name } and my age is ${ age }`; console.log(message); //My name is Lokesh and my age is 35
Template strings can be multi-line
Not like with regular strings where you use plus (+
) character to concatenate multi-line strings, template strings do not need plus character.
const name: String = 'Lokesh'; const age: number = 35; let message: string = `My name is ${ name } and my age is ${ age }`; //Output My name is Lokesh and my age is 35
Please notice that multi-line template strings output the string which is formatted with new line characters.
Drop me your questions in comments section.
Happy Learning !!