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

JavaScript Loops, Arrays and Objects - Challenge Task 1 of 2

I have completed the "Use a for in loop to log each of the property names of the shanghai object to the console." and followed the example code from the tutorial video. BUT when i tried to complete the challenge. I got it wrong.

var person = {
  name : 'Sarah',
  country : 'US',
  age : 35,
  treehouseStudent : true,
  skills : ['JavaScript', 'HTML', 'CSS']
};

for (prop in person) {
  console.log(prop, ': ', person[prop]);

}

BUT when i completed the challenge, the code looked like this

var shanghai = {
  population: 14.35e6,
  longitude: '31.2000 N',
  latitude: '121.5000 E',
  country: 'CHN'
};
for (var prop in shanghai) {
  console.log(prop, shanghai[prop]);
}

So why did I have to put in "var" for the code challenge, and NOT for the example above. This has confused me. Please can someone explain why this is?

2 Answers

Steven Parker
Steven Parker
243,656 Points

Without the "var" the name "prop" becomes a global variable by implication.

But implicit global declarations are not allowed in "strict" mode, which is how the challenge operates.

You can turn on this mode of evaluation in the workspace by putting this as the top line of your script:

use "strict";

This issue caused alot of confusion, why is the module teaching us not use for (var " ". Consistency helps the learning process.

Steven Parker
Steven Parker
243,656 Points

Declaring all variables is considered a "best practice", even when strict mode is not being used.