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 Arrays Loop Through Arrays Using a 'for' Loop to Iterate Over an Array

Alex Francis
Alex Francis
10,215 Points

Is 'let' compulsory when declaring 'i' in the for loop?

I've noticed that the following code will work in the browser (Chrome):

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

The output is:

0
1
2
3
4
5
6
7
8
9

With that in mind, I am interested whether it is technically compulsory to use let to declare i in the for loop syntax.

Does this have something to do with 'strict mode' and avoiding potentially buggy code?

Thanks! :)

2 Answers

Jason Larson
Jason Larson
5,485 Points

You are correct. In JavaScript, by default you are not required to declare variables before using them, so the following statements are basically the same (other than scope):

i = 0;
let i = 0;
var i = 0;

The problems come in when strict mode is enabled or using other frameworks like React that require strict mode. Additionally, you can run into some bugs that are harder to troubleshoot when you don't declare the variable type because they will become global variables by default.

Alex Francis
Alex Francis
10,215 Points

That is very interesting.

I suppose i in this case would be automatically initialised as a let? Or would it be a var?

It sounds like it would be best to always declare i properly in a for loop then (using let).

Otherwise, if i is being automatically created as a global variable, would that mean that any other javascript run on that page would be able to access it? So if another i is used in a separate script it could cause collision problems?

Thanks!