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 Using `for in` to Loop Through an Object's Properties

Thanitsak Leuangsupornpong
Thanitsak Leuangsupornpong
7,490 Points

Why there no var before the prop in teacher video?

If it about store the information in the the parameter,where can I use parameter. Where are the parameter? in function only ? ,or what other place?

2 Answers

for (var i in array){ console.log(i); }

is basically the same as

for (i in array) console.log(i); }

The teacher did it like option 2 in the video, but that is not accepted as an answer in the challenge, you need to use option 1 there.

JavaScript is fairly forgiving of things like this, but it's actually creating a global variable, which can be dangerous if it conflicts with another variable with the same name.

He definitely should have either included the var keyword, or declared the variable earlier in the code before using it.

It's not a parameter because for is not a function, it's built into JavaScript.

Oğulcan Girginc
Oğulcan Girginc
24,848 Points

Which one is a better practice in this case; including the var keyword or declaring the variable earlier in the code?

Best practices and a lot of linters and pre-processors would suggest that all variables should be declared at the top/beginning of their scope (start of the script, or first in a function), and preferably with just one var keyword, separated by commas:

script.js
var myVar,
    emptyArray = [],
    emptyObject = {},
    aString = 'here is a string',
    aNumber = 123,
    i,
    finishWithASemiColon;

for (i=0, i<aNumber; i++) {
  console.log(i);
}