I have the following code for ECMAScript 6 template literals:
let person = {name: 'John Smith'};
let tpl = `My name is ${person.name}.`;
let MyVar = "My name is " + person.name + ".";
console.log("template literal= " + tpl);
console.log("my variable = " + MyVar);
The output is as follows:
template literal= My name is John Smith.
my variable = My name is John Smith.
This is the fiddle.
I tried searching for the exact difference, but I couldn't find it, What is the difference between the following two statements?
let tpl = `My name is ${person.name}.`;
And
let MyVar = "My name is "+ person.name+".";
I am already able to get the string MyVar
concatenated with person.name
here, so what would be the scenario to use the template literal in?
If you are using template literals only with placeholders (e.g.
`Hello ${person.name}`
) like in the question's example, then the result is the same as just concatenating strings. Subjectively it looks better and is easier to read, especially for multi-line strings or strings containing both'
and"
since you don't have to escape those characters any more.Readability is a great feature, but the most interesting thing about templates are Tagged template literals:
In the third line of this example, a function named
tag
is called. The content of the template string is split into multiple variables, that you can access in the arguments of thetag
function: literal sections (in this example the value ofstrArr[0]
isMy name is
and the value ofstrArr[1]
is!
) and substitutions (John Smith
). The template literal will be evaluated to whatever thetag
function returns.The ECMAScript wiki lists some possible use cases, like automatically escaping or encoding input, or localization. You could create a tag function named
msg
that looks up the literal parts likeMy name is
and substitutes them with translations into the current locale's language, for example into German:The value returned by the tag function doesn't even have to be a string. You could create a tag function named
$
which evaluates the string and uses it as a query selector to return a collection of DOM nodes, like in this example: