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!

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

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?

var shanghai = {
  population: 14.35e6,
  longitude: '31.2000 N',
  latitude: '121.5000 E',
  country: 'CHN'

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

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! :)

8,841 Points

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

You're very welcome =]