Template Literals in JavaScript6

If you have used any templating engines like handlebars or ejs, you know how powerful they are. Templates help to build reusable code blocks.

Replacing string concatenation operator

Say we have 2 string variables and we are going to concatenate them to form a new sentence.

1
2
3
4
var name = "Joby";
var age = 30;
var sentence = name + " is " + age + " years old.";
console.log(sentence); // Joby is 30 years old.

Let me now show you how to achieve the same concatenation using templates in ES6.

1
2
3
4
var name = "Joby";
var age = 30;
var sentence = `${name} is ${age} years old.`;
console.log(sentence); // Joby is 30 years old.

Note that no more painful concatenation using + operator. A template starts and ends with backtick(`). Variables are placed using ${} syntax.

Expression inside substitution

You can write an expression inside template literal.

1
2
3
4
var num1 = 2;
var num2 = 4;
var sum = `${num1 + num2 + 3}`;
console.log(sum); // 9

The expression inside the placeholder is evaluated.

Associating tag to template

Let us understand the tag concept step by step.

Here I have 2 variables and 1 template.

1
2
3
varname = "Joby";
varage = 30;
varsentence = `${name} is ${age} years old.`;

You now can easily guess the value of sentence. Now I am going to apply a tag upperCaseto the template.

1
2
3
varname = "Joby";
varage = 30;
varsentence = upperCase `${name} is ${age} years old.`;

The tag upperCaseis actually a function which is applied on the template. So we need to define that function.

1
2
3
4
functionupperCase(strings, ...values){
    console.log(strings);
    console.log(values);
}

The function accepts 2 parameters. What will be the value of stringsand values? Let me try to explain.

When ever JavaScript engine sees a tag function, it chops the template to different parts. It chops string part and value part. For example if we chop,

1
${name} is ${age} years old.

we get

1
2
3
4
Joby
is
30
years old.

It then groups all strings to stringsarray. So stringsarray will contain

1
["", "is", " years old."]

valuesarray will contain

1
["Joby", "30"]

Now we know what are the values received by upperCasetag function. Now let us decide what that function returns. See the modified upperCasefunction below.

1
2
3
4
5
functionupperCase(strings, ...values){
    console.log(strings);
    console.log(values);
    returnstrings.join(' ').toUpperCase() + values.join(' ').toUpperCase();
}

Basically the function is grouping stringsand valuesseparately. Then transforming them to upper case and again joining them before return. Its time to see the output.

1
2
3
4
var name = "Joby";
var age = 30;
var sentence = upperCase `${name} is ${age} years old.`;
console.log(sentence); // IS   YEARS OLD.JOBY 30

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *