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 Tracking Data Using Objects Accessing All of the Properties in an Object

derekverrilli
derekverrilli
8,841 Points

Why do we need to use the var keyword?

I'm curious why not using the 'var' keyword causes an error when in the video, Dave doesn't use it?

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

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

2 Answers

Hey Derek,

I'm sure this was just a mistake in the video. In the first part of the video, he uses the var keyword, but he does not in the Workspaces part. I see where you might get confused.

It is a very good practice to use the var keyword when initializing variables for loops so that the variable created doesn't accidentally get hoisted into the global scope. But, I'll tag Dave McFarland so that he can give his answer! :)

derekverrilli
derekverrilli
8,841 Points

Definitely makes sense and I figured as much. Thanks for the reply :)

You're very welcome =]