Search code examples
javascriptstring-interpolation

JavaScript string interpolation on strings assigned as property values in objects


I have the following object:

var obj = {
   number: "123456789"
   tel: `The clients phone number is ${number}. Please call him!`

How can I insert the number value in the tel-string?


Solution

  • You cannot access the object while is being initialized. You can either assign the property after the object initialization or you can define a getter property:

    const obj = {
      number: "123456789",
      get tel() {
        return `The clients phone number is ${this.number}. Please call him!`;
      }
    };
    
    console.log(obj.tel);