Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects Accessing All of the Properties in an Object

Richard Stover
seal-mask
.a{fill-rule:evenodd;}techdegree
Richard Stover
Full Stack JavaScript Techdegree Student 8,838 Points

Challenge task code global property error

I am receiving an error with the attached code and do not see the reason.

"Bummer: There was an error with your code: ReferenceError: Strict mode forbids implicit creation of global property 'test'"

Can someone please point out the syntax error to me?

script.js
var shanghai = {
  population: 14.35e6,
  longitude: '31.2000 N',
  latitude: '121.5000 E',
  country: 'CHN'
};

for (test in shanghai){
 console.log(test); 
}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Objects</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

1 Answer

Nicole Antonino
Nicole Antonino
12,809 Points

You didn't write the correct syntax. You forgot to declare with a const at the beginning. So yours should look like this:

for (const test in shanghai){
 console.log(test); 
}

For reference here is the correct syntax according to the MDN:

Richard Stover
seal-mask
.a{fill-rule:evenodd;}techdegree
Richard Stover
Full Stack JavaScript Techdegree Student 8,838 Points

huh..I had a feeling it was variable declaration thing.

But then why did my original code work in a blank workspace I pasted it into?

Nicole Antonino
Nicole Antonino
12,809 Points

Not sure! Hard to say without seeing the code directly. But if you declared a variable with the same name before the for...in loop then that might have done it.