JavaScript string interpolation on strings assigned as property values in objects

Viewed 637

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?

1 Answers

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);

Related