Didn't declare variable; why does it run?


#1

In the final For Loop exercise (the first one where we actually construct a for loop unfortunately, but I digress...) I forgot to declare the variable i before I used it, which I realized when I came to the forums to see what others did.

However, the code appears to run as intended... My question is why does this run? Is it just a trick of the CodeCademy console and wouldn't work elsewhere? Or is there something else at play here?

Thanks all!
frisby

https://www.codecademy.com/courses/javascript-beginner-en-NhsaT/1/3?curriculum_id=506324b3a7dffd00020bf661#


for (i = 100; i > 0; i-=5) {
    console.log(i);
}


#2

When you assign a value to a variable without declaring it, it is treated as a property of the window object meaning it is global on the whole site, which is toooooo global believe me. I once made a test and you can see the value of i even when you turn over to the next exercise. So better declare your variables as global as necessary and as local as possible.


#3

Thank you for your help, haxor789. I think I do recall experiencing the event you describe in the Ruby track...

So am I understanding correctly that this is a, um, feature :slight_smile: intrinsic to CodeCademy's system rather than JS in general?

Also, does global on the whole site include other tracks, browsers, users, etc. or just my current browser/computer/track? Will refreshing the browser do anything?

Finally, will properly declaring i revert its scope to a less ├╝ber-global scale?

Thanks again!


Didn't declare a variable part II
#4

I guess it's generally not a good idea to use this in javaScript to make a global variable and it should only effect your current browser and only as long as you don't refresh the page and thereby reset the js. But you might run some test with it. And about fixing the i, no it won't revert it, but once you've refreshed the page it won't do the same thing again :slight_smile:


#5

Ahhh I see! Thanks again for your help, @haxor789. I'll try not to unleash too many world-dominating variables in the future :grin:


#6

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.