DEV Community

Abhirup Datta
Abhirup Datta

Posted on

Template literals in Javascript

A sample template literal

const x = `This is template literal`;
console.log(x);
Enter fullscreen mode Exit fullscreen mode

Which will print

Console output

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.


Latest comments (0)