3

I'm trying to re-use a template literal in javascript.

This isn't working:

let int;
let temp= `Number is: ${int}`;
console.log(temp)
// Number is: undefined
int = 1;
console.log(temp)
// Number is: undefined
int = 2;
console.log(temp)
// Number is: undefined

I thought that changing int variable will dynamicaly change in the template. but i learned otherwise :D

Is it even possible and if so what is the right way of doing it?

Thanks.

fedesc
  • 2,554
  • 2
  • 23
  • 39

3 Answers3

9

Simply make it to be returned by a function:

let int;
let temp= () => `Number is: ${int}`;
console.log(temp())
// Number is: undefined
int = 1;
console.log(temp())
// Number is: 1
int = 2;
console.log(temp())
// Number is: 2
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
  • 2
    You could pass `int` as a parameter instead of taking closure over the variable – adiga May 13 '19 at 12:42
  • 1
    As I do not know what's the use for the OP code, I prefer to point out the problem with the minimum edit possible to the OP code so he can focus on it. – Mosè Raguzzini May 13 '19 at 12:46
3

Your best option is to create a function for this.

function getTemp(int) {
  return `Number is: ${int}`;
}


let int;
console.log(getTemp(int))
// Number is: undefined
int = 1;
console.log(getTemp(int))
// Number is: undefined
int = 2;
console.log(getTemp(int))
// Number is: undefined
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
3

You can simply use Tagged templates

let temp= (num) => `Number is: ${num}`;

console.log(temp `1`);
console.log(temp `2`)
amrender singh
  • 7,949
  • 3
  • 22
  • 28