Home

String Interpolation - ES6 Template Literals in JavaScript

ES2015 i.e., ES6 has introduced a new way to concat strings with variables or create multi-line strings in JavaScript. This feature is called template literals or template strings. Let's see the old school issues without template literals and how they solve those issues.

Multiline strings

If you want to log a multi-line message some thing like below, you can use the template strings (or template literals):

Hi Dev!
Have a nice day :)

To make this possible using ES6, you can just do:

var text = `Hi Dev!
Have a nice day :)`;

console.log(text);

Without ES5, you should use \n, to achieve this:

var text = 'Hi Dev!\nHave a nice day :)';

console.log(text);

String concatentation

The string interpolation can be used instead of string concatenation while using variables and expressions to construct lengthy strings.

var name = 'Dev';

// With ES6 interpolation
console.log(`Hi ${name}! The date is ${new Date().toDateString()}`);

// Without interpolation, a lot of break and you might miss a space or misspell something, if the length of string increases
console.log('Hi ' + name + '! The date is ' + new Date().toDateString());

Uses

The concept of ES6 template strings is most useful when you create markup using JavaScript like the example shown below:

//If you try to do this example without template literals, it will create a hard-to-read code
const author = {
  name: 'An Utopian',
  title: 'An amamzing witer ;)',
};

const markup = `
 <div class="author">
    <h2 class="author__name">${author.name}</h2>
    <p class="author__title">${author.title}</p>
 </div>
`;


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments