Skywooo
Skywooo

Reputation: 97

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?

Upvotes: 3

Views: 1138

Answers (1)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827496

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

Upvotes: 8

Related Questions