Search code examples
javascriptstringliteralstemplate-literalsbackticks

Extra element in string literal array of template literals


For Example, on running the below code -

let a = 5;
let b = 10;

function print(strings, ...values) {
  console.log(strings[0]);
  console.log(strings[1]);
  console.log(strings[2]);
  console.log(values[0]);
  console.log(values[1]);
}

print `add${a + b}mul${a - b}`;

Following Output is received -

"add"
"mul"
""
15
-5

Why there is an extra string literal at the end, even when i provided only only two, add and mul ?


Solution

  • Because there's empty string "" after the ${a - b}. The last index simply cannot be removed, because it is possible that there's a non-empty string. You get the same behavior by placing two expressions side by side without any string between them (${...}${...}). Example:

    function tag(...all) {
      console.log(all);
    }
    
    tag `a${1}b${2}${3}c`;

    If you need to get rid of empty strings, you can filter the string array using Array.filter, here's an example:

    function tag(strings, ...values) {
      console.log(strings.filter(Boolean)); // filters arary, "" == false
      console.log(values);
    }
    
    tag `a${1}b${2}${3}c${4}d${5}`;

    Output is

    ["a","b","c","d"]
    

    instead of:

    ["a","b","","c","d",""]