Javacript Template Literals scope

70 views Asked by At

I want to declare a variable inside a template literal and use it in the same template later is that possible? If this is not possible it seems like a missing feature to me.

const tmp = tag`
 some random text, ${let myvar = 55} more text,
 even more text ${myvar}
`
1

There are 1 answers

3
Dimava On

Template literals can literally return only two things:

  • the parts they consist of
  • the values in-between

If you want a variable shared between between different values, they have to be closured
If you want to use some calculation, you have to pass in a function

const tmp = (() => {
  let myvar;
  return tag`
   some random text, ${() => myvar = 55} more text,
   even more text ${() => myvar}
   and the double text ${() => myvar + myvar}
  `
})()