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,402
  • 2
  • 19
  • 35

3 Answers3

8

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
  • 14,237
  • 29
  • 40
  • 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
  • 5,616
  • 1
  • 18
  • 49
2

You can simply use Tagged templates

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

console.log(temp `1`);
console.log(temp `2`)
amrender singh
  • 7,430
  • 3
  • 20
  • 27