3

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?

2
  • 2
    Declare and assign a value to number variable before declaring the obj variable. Commented Oct 15, 2019 at 13:38
  • ^^ That. The properties don't exist until you terminate the object initialisation, so number does not yet exist as a variable. Alternatively, don't add tel until afterwards... obj.tel = `The clients phone number is ${obj.number}. Please call him!` Commented Oct 15, 2019 at 13:39

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Dalorzo: FWIW, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… says it's supported in Edge.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.