I am learning JS templates and found the following example:
function hash(a, b) {
return a + "##" + b;
}
let count = 3;
let a = `foo ${hash ` bar ${count} baz`}`;
console.log(a);
result is : foo bar , baz##3
Could anyone explain:
- Why hash function is called without using parentheses –
()
? - This result –
foo bar , baz##3
?
2
Answers
The hash function is called without parentheses because it’s used as a "tag" for the template literal. This syntax allows the hash function to process the template literal’s parts and values.
The result "foo bar , baz##3" is formed because the hash function combines the string parts and values from the template literal, adding "##" between them.
hash
is being used as a tagged template. When a function is called with``
, the first argument is an array of the constant string values in the template literal. The other arguments are the values of the expressions in${}
.In this case, the parameter
a
inhash
is[' bar ', ' baz']
, andb
is3
(the value of the variablecount
). When an array is concatenated with a string,toString()
is implicitly called, with joins the elements together with a comma, so the result isbar , baz##3
, which gets interpolated into the template literal assigned to the variablea
.