HappyCoding HappyCoding - 3 months ago 20
Javascript Question

JavaScript Template example

Here is a demo which was written by Scott Allen:



var x = 1;
var y = 3;
var upper = function (string, ...values) {
var result = '';
for (let i = 0; i < string.length; i++) {
result += string[i];
if (i < values.length) {
result += values[i]
}
}
console.log('string', string)
console.log('values', values)
return result.toUpperCase()
};
var result = upper `${x} + ${y} is ${x + y}`
console.log(result)





My question: How does javascript detect array string and array values via

${x} + ${y} is ${x + y}
?

Is it: split
${x} + ${y} is ${x + y}
and select the parts which are outside
${}
?

And second question: I've wrapped
${x} + ${y} is ${x + y}
by
()
,
string
and
values
were changed but same result like the first example. Is it right syntax? Or should I avoid using
()
in this case?



var x = 1;
var y = 3;
var upper = function (string, ...values) {
var result = '';
for (let i = 0; i < string.length; i++) {
result += string[i];
if (i < values.length) {
result += values[i]
}
}
console.log('string', string)
console.log('values', values)
return result.toUpperCase()
};
var result = upper (`${x} + ${y} is ${x + y}`)
console.log(result)





p/s: I've searched in Google Search with keywords javascript template but no document mentioned about it.

Answer

p/s: I've searched in Google Search with keywords javascript template but no document mentioned about it.

Try using search term Template literals

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:

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