skip to Main Content

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:

  1. Why hash function is called without using parentheses –()?
  2. This result – foo bar , baz##3?

2

Answers


    1. 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.

    2. 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.

    Login or Signup to reply.
  1. 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 in hash is [' bar ', ' baz'], and b is 3 (the value of the variable count). When an array is concatenated with a string, toString() is implicitly called, with joins the elements together with a comma, so the result is bar , baz##3, which gets interpolated into the template literal assigned to the variable a.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search