Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Understanding "this" in JavaScript

How do I call all cities in one line?

Great WS, straight forward and easy to follow. How do I call all cities without calling one by one?

var City = function(name, state) {
    this.name = name || 'Portland';
    this.state = state || 'Oregon';
    this.printMyCityAndState = function() {
      console.log("My city is " + this.name + ", and my state is " + this.state);
    };
};

portland = new City();
seattle = new City('Seattle', 'Washington');
salem = new City('Salem');
vancouver = new City('Vancouver', 'Washington');

portland.printMyCityAndState();
seattle.printMyCityAndState();
salem.printMyCityAndState();
vancouver.printMyCityAndState();

3 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi johnnyesper,

You can store each City instance within an array and/or object and then iterate over it as shown below.

Using an array

var cities = [
  new City(),
  new City('Seattle', 'Washington'),
  new City('Salem'),
  new City('Vancouver', 'Washington')
];

for (var c in cities) {
  // c = numeric array id
  // cities[c] = `City` instance
  cities[c].printMyCityAndState();
}

Using an object (if you want key/value pairs for quicker identification)

var cities = {
  portland: new City(),
  seattle: new City('Seattle', 'Washington'),
  salem: new City('Salem'),
  vancouver: new City('Vancouver', 'Washington')
};

for (var c in cities) {
  // c = key (city name)
  // cities[c] = `City` instance
  cities[c].printMyCityAndState();
}

Happy coding!

Matthew Smart
Matthew Smart
12,567 Points

A bit of code would help, it means we don't haver to watch the whole video to figure out what you mean

Your right. It's in the question now.

Thanks