A sample template literal
const x = `This is template literal`;
console.log(x);
Which will print
Template literal is mainly used in two ways
- String interpolation
- Tagged functions or Tagged templates
In this blog, we will discuss about String interpolation.
const human = {
   age: 28,
   country: 'India'
}
const intro = `My age is ${human.age} and I am from ${human.country}`;
console.log(intro);
We are interpolating the name and age property of human object.
If we try to use single quoted(or double quoted) strings we have to write this:
const intro = 'My age is '+human.age+' and I am from '+human.country;
We can write any javascript logic between the ${ }.
This enable us to write easily understandable logic.
const human = {
   age: 28,
   country: 'India'
}
const intro = `I am ${human.age > 20 ? 'adult' : 'juvenile'}`
console.log(intro);
The equivalent of writing this in single quote
const human = {
   age: 28,
   country: 'India'
}
const intro = 'I am '+ ( human.age > 20 ? 'adult' : 'juvenile' );
console.log(intro);
String interpolation can be useful in React JSX when writing conditional  className.
Suppose, we want to apply btn-highlight when the button is to be highlighted and btn as a normal button. We can take the btnas a common word and append -highlight as per condition.
 


 
    
Top comments (0)