Naeem Shaikh Naeem Shaikh - 2 months ago 15
Node.js Question

ES6 Template Literals Vs concatenated strings

I have the following code for Ecma-Script-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 couldn't find it,
My question is what is the difference between these 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 ?

Answer

The result of using template literals like in the question's example isn't that different from 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 to escape those characters any more.
Readability is a great feature, but the most interesting thing about templates are Tagged template strings.

Basically, tag `My name is ${person.name}.` calls a function named tag with the literal sections (in this example My name is and .) and the substitutions (John Smith) that you can access in the arguments. The template literal will be evaluated to whatever the tag function returns.

The ECMAScript wiki lists some use cases, like auto escaping or localization. You could create a tag function named msg that looks up the literal parts like My name is and substitutes them with translations into the current locale's language, for example into German:

console.log(msg`My name is ${person.name}.`) // Output: Mein Name ist John Smith.

The value returned by the tag function doesn't even have to be a string. This query selector example is supposed to return a collection of DOM nodes:

$`a.${className}[href=~'//${domain}/']`
Comments