0

This is the code

const restaurant = {
    name: 'Ichiran Ramen',
    address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
    city: 'Brooklyn',
    state: 'NY',
    zipcode: '11206',

I want to create a variable "fullAddress" which should point to a string using the information from restaurant fullAdress should have address city state and zipcode.

my approach is

let fullAddress = restaurant.address;
fullAddress += restaurant.city;
fullAddress += restaurant.state;
fullAddress += restaurant.zipcode;

but this seems odd to me and lengthy and it is not having spaces in between.

any help will be highly appreciated.

2

2 Answers 2

3

You can define a getter property

const restaurant = {
    name: 'Ichiran Ramen',
    address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
    city: 'Brooklyn',
    state: 'NY',
    zipcode: '11206',
    get fullAddress() {
      const { address, city, state, zipcode } = this;
      return `${address} ${city} ${state} ${zipcode}`;
    }
}

console.log(restaurant.fullAddress);

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

2 Comments

Please add your answer to the identified duplicate question rather than answering this one.
I think the 2 questions are sligtly different. The answer you identified regards objects modification, this one is about getting values.
1

Your approach is not overly verbose and it is defensibly clear to read, however you aren't concatenating a comma and space in between the address components. To get the correct result using your approach:

let fullAddress = restaurant.address;
fullAddress += ', ';
fullAddress += restaurant.city;
fullAddress += ', ';
fullAddress += restaurant.state;
fullAddress += ', ';
fullAddress += restaurant.zipcode;

However, if you would like a more succinct approach, and assuming you are working in a modern (ES6) environment, you can use template literals for this.

For example, if you wanted the final string to be 123 Johnson Ave, Brooklyn, NY, 11206

You would write this as:

const fullAddress = `${restaurant.address}, ${restaurant.city}, ${restaurant.state}, ${restaurant.zipcode}`;

Note that the syntax for template literals uses backticks, not normal quotes.

More information about template literals on MDN.

Comments

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.