All you need to know about Template literals in ES6: JavaScript

JavaScript , 0 Comments

Template literals (Template strings) are one of the amazing features of JavaScript. You can use multi-line strings, string interpolation and more features with them and this is the easiest way to improve your JavaScript code readability. Introduced in ES6.

Okay, that’s great! Show me an example.

Template literals in ES6 Syntax

const str = `this is what it looks like`;

Don’t get confused, It is still a string, but using these back-ticks you can really do some amazing stuff.

#1 String Concatenation

Template literals in ES6 will amazingly improve your code readability here I’ll show you how?

Consider the following example:

var person = {
  name: 'Katherine',
  nickName: 'Kate',

Above, We have an object personpe. Object person has two properties name and nickName and we want to console.log these values along with some text, As normal String Concatenation its looks like this

console.log('Hi, I\'m ' + + '! Call me "' + p.nickName + '".');

I just covered two annoying features in this String Concatenation, First, we have to escape our apostrophe with backslashes. And secondly, trying to figure out what in the world the code is trying to say. The single and double quote things get very confusing.

Now try it with Template literals

 console.log(`Hi, I'm ${}! Call me "${p.nickName}".`); 

See, this is easily readable, clean and less confusing, you can easily differentiate between variables and text.

This is the output of both example

Hi, I'm Katherine! Call me "Kate".

Whenever you want to add any variable inside Template literals all you need to add is dollar sign with curly braces:


template literals buginint

#2 Multi-line strings/Line Break

Hers is Template literals are shining stars. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

console.log('line 1 text \n' +
'line 2 text \n' + 
'and so on');
// Output 
// line 1 text 
// line 2 text 
// and so on

Here is the Template literals magic.

console.log(`line 1 text
line 2 text
and so on`);
// Output 
// line 1 text 
// line 2 text 
// and so on

That because, Newline characters, tabs, spaces are part of it.

Note: This is very important to remember as it can be both a blessing and a curse. 

#3 Expression Interpolation

Yes, you can use expressions while concatenating strings using Template literals.

Here is a quick example of normal strings concatenation:-

var a = 5;
var b = 10;
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
// Fifteen is 15 and
// not 20.

Now with Template literals.

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// Fifteen is 15 and
// not 20.

#4 Nesting templates

In certain cases, nesting a template is the easiest and perhaps more readable way to have configurable strings. Within a backtick template, it is simple to allow inner backticks simply by using them inside a placeholder ${ } within the template. For instance, if condition a is true: then return this templated literal.

In ES5:

var classes = 'header'
classes += (isLargeScreen() ?
   '' : item.isCollapsed ?
     ' icon-expander' : ' icon-collapser');

In ES2015 with template literals and without nesting:

const classes = `header ${ isLargeScreen() ? '' :
    (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;

In ES2015 with nested template literals:

const classes = `header ${ isLargeScreen() ? '' :
 `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;

#5 Tagged templates

A tagged template is a function call that uses a template literal from which to get its arguments.

Hers is a tagged function example:

greet`I'm ${name}. I'm ${age} years old.`;

Don’t get yourself confused, In the above example, greet is a function that takes three arguments

1. The first parameter is an array containing all of the text from our template literal. 

2. The 2nd to infinity parameters in our function are the variables to be inserted into our tag function.

Here I’ll show you the greet function from inside.

// creating name and age variable 
var name = 'buginit';
var age = 1; 

// creating a greet function
function greet(strings, name, age) {
  var str0 = strings[0]; // "I'm"
  var str1 = strings[1]; // "I'm"
  var str2 = strings[2]; // "years old"
  console.log(name) // buginit
  console.log(age) // 1

// calling greet function here and passing 
// name and age variable that we created above
greet`I'm ${name}. I'm ${age} years old.`;

Hope you understand.

Also check this: A Complete Guide: Tagged Template Literal In JavaScript

#6 Raw strings

The special raw property, available on the first argument to the tag function, allows you to access the raw strings as they were entered. For example:

function tag(strings) {

tag`string text line 1 \n string text line 2`;
// string text line 1 \n string text line 2

This will log including the two characters '\' and 'n'

In addition, the String.raw() method exists to create raw strings just like the default template function and string concatenation would create.

var str = String.raw`Hi\n${2+3}!`;
// "Hi\n5!"

// 6

// "H,i,\,n,5,!"

Sorry for the long Post, But If it helped please share and support.

Leave a Reply

Your email address will not be published.