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
|
var name = "Joby" ; var age = 30; var sentence = `${name} is ${age} years old.`; |
You now can easily guess the value of sentence. Now I am going to apply a tag upperCase
to the template.
1
2
3
|
var name = "Joby" ; var age = 30; var sentence = upperCase `${name} is ${age} years old.`; |
The tag upperCase
is actually a function which is applied on the template. So we need to define that function.
1
2
3
4
|
function upperCase(strings, ...values){ console.log(strings); console.log(values); } |
The function accepts 2 parameters. What will be the value of strings
and 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 strings
array. So strings
array will contain
1
|
[ "" , "is" , " years old." ] |
values
array will contain
1
|
[ "Joby" , "30" ] |
Now we know what are the values received by upperCase
tag function. Now let us decide what that function returns. See the modified upperCase
function below.
1
2
3
4
5
|
function upperCase(strings, ...values){ console.log(strings); console.log(values); return strings.join( ' ' ).toUpperCase() + values.join( ' ' ).toUpperCase(); } |
Basically the function is grouping strings
and values
separately. 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 |
Recent Comments