Question:
What is Scope?
Answer:
Scope refers to the visibility of a variable from within sections of your code.
There are 2 types of scope: Local and Global.
Question:
What is local scope?
Answer:
A variable declared inside a function is only visible inside that function.
Other functions do not know anything about that variable, and cannot "see" it.
Therefore, other functions cannot access that variable, and if you try to use a
variable that is not visible, your code will not work properly.
Variables declared without the var keyword are global.
This is why you should always use the var keyword to declare variables,
to avoid the confusion of using one variable when you think you are using another.
Question:
What is global scope?
Answer:
Variables that are declared outside of functions are visible throughout your entire code,
and therefore referred to as global. Global variables are usually declared at the top of
your JavaScript file, with comments explaining their uses.
Question:
When should I use one or the other?
Answer:
Most variables should be local - inside functions, keeping functions autonomous and independent
from each other. That way, if you need to make a change to a function, you do not have to worry
about breaking other functions. Also, if your function manipulates a variable, you do not have to worry
about another function using that same variable and depending on the old value before
your function changed it.
Global variables are often used as constants - variables whose values do not change once they are set.
For example, your code might need to know what type of browser is in use. A global variable
could be assigned the browser type, then the rest of your code could check that variable and perform accordingly.
Another example of a global variable might be an array of students that would be used by several functions...
one to calculate totals, one to calculate percentage of possible points, and another function to display the results.