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 trialbrevans26
15,198 PointsVar key name
Why in the video Dave mentions we can choose any name we want for the var key but in the exercise I get the message: It's a good idea to use the var
keyword in a for in
loop like this: for (var key in shanghai)
.?
var shanghai = {
population: 14.35e6,
longitude: '31.2000 N',
latitude: '121.5000 E',
country: 'CHN'
};
for (location in shanghai) {
console.log(location, ': ', shanghai[location]);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Objects</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
2 Answers
Jennifer Nordell
Treehouse TeacherHi there! The reason that using a var
inside a for loop is a good idea is because it limits the scope of the variable to only that function. This is especially important if you are working with a team of people. If someone else also has written a global variable named location
then your results might be very different from what you expect them to be.
If you're using "strict mode", this will throw an error as it is a global variable.
Hope this helps!
Steven Parker
231,269 PointsYou can choose any name to represent the key (as here you have chosen "location"), but you still need the word "var" in front of it:
for (var location in shanghai) {
brevans26
15,198 PointsThank you Steven!
Steven Parker
231,269 PointsSteven Parker
231,269 PointsFYI: There's no function in this challenge, so the scope restriction does not apply here.
Jennifer Nordell
Treehouse TeacherJennifer Nordell
Treehouse TeacherTrue, but the question refers to why it's a good idea. And this is why it's a good idea
brevans26
15,198 Pointsbrevans26
15,198 PointsThank you Jennifer!
I was confused. I was following him on my workspace as he was explaining the concept in the video and he did not use the word var in his example. He just wrote:
Thank you for clarifying that.
Steven Parker
231,269 PointsSteven Parker
231,269 PointsNaughty instructor! It's a missed opportunity to exemplify "best practices".
Jennifer Nordell
Treehouse TeacherJennifer Nordell
Treehouse Teacherbrevans26 as Steven Parker notes, it's not really necessary in this case as scope is not really involved here, but it doesn't hurt anything and it is a very good habit to get into