0

I have a small question about for loop in Js: Why i have to write:

for (let i; i < 10; i++) {}

Meanwhile, the code will run correctly if i write:

for (i; i < 10; i++) {}

Thanks for your answer!

  • If it works doesn't mean that you should. If you use ```let``` then the variable is __declared within the scope__ you are in __for ex:-function__. If you don't use ```let```, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object where it then attaches itself. It is then very similar to a global variable and __*it can overwrite existing variables*__ which would break your entire code and is very dangerous as it might then become very difficult to debug. – Uzair Saiyed Jun 13 '21 at 09:00

1 Answers1

0

It works because JavaScript allows using undeclared variables. But if you enable strict mode using 'use strict', it will not work as you never declared i. It’s better to use the first example you provided.

addeo
  • 34
  • 4