0

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 ?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Adesh Khanna
  • 172
  • 2
  • 9

1 Answers1

1

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",""]
mozkomor05
  • 1,367
  • 11
  • 21