0

This works:

hero = "batman";
sidekick = "robin";
villain = "the joker"

function f(strings, good, helper, bad) {
    console.log(strings); //expected: " and must team up to defeat "
    console.log(good); //expect: "batman"
    console.log(helper);//expect: "robin"
    console.log(bad);//expect: "the joker"
}

f`${hero} and ${sidekick} must team up to defeat ${villain}`;

However when I store the template literal in a variable and try to pass the variable to the function it does not work:

hero = "batman";
sidekick = "robin";
villain = "the joker"

sentence = `${hero} and ${sidekick} must team up to defeat ${villain}`;

function f(strings, good, helper, bad) {
    console.log(strings); //expected: " and must team up to defeat "
    console.log(good); //expect: "batman"
    console.log(helper);//expect: "robin"
    console.log(bad);//expect: "the joker"
}

fsentence;

Is there a work-around?

  • 1
    Why do you need this? `sentence` is just a string. You can't defer it's evaluation for later to use. – adiga Jul 29 '20 at 15:04
  • 2
    Template literals are evaluated when encountered. You can't just "store" an unprocessed template literal in a variable. You can make a function when called will evaluate the template literal - that's the closest you can really get to. – VLAZ Jul 29 '20 at 15:05
  • @VLAZ Okay, thanks – tonitone117 Jul 29 '20 at 15:07
  • 3
    You can do ``const sentence = (t) => t`${hero} and ${sidekick} must team up to defeat ${villain}`;`` and then call `sentence(f)` but it's rather weird to pass in the tag function. Normally you'd pass the substitution values – Bergi Jul 29 '20 at 15:12

0 Answers0