18th March 2012 - 6 minutes read time
I have seen a lot of this sort of thing, so though I would put together a quick lesson in JavaScript variable scope. There are some important differences between local and global variables in JavaScript that will cause grey hairs if you don't know what's going on.
Scope is something that dictates what variables can be seen by code. If a variable is created inside a function then it can be said to be local as only the locally running code can see it. A variable that can be accessed by any part of the code is said to be global. This is special in JavaScript, which I will come onto later.
This scope concept is important as if a variable is outside the current scope then the code can't see it. Everything in JavaScript is a variable so understanding how and when variables can be accessed is important.
To create a local variable in JavaScript do this: