Scope Examples
JavaScript and PHP do not require you to declare a variable before use. This can be handy when you just need to get something done but problematic when troubleshooting.
For example, in JavaScript, a variable declared outside of a function is available inside a function:
var name = "Jonathan";
function showme()
{
alert(name); // will display "Jonathan"
}
showme();
A variable declared within a function will not be available outside of a function.
function showme()
{
var name = "Jonathan";
}
showme();
alert(name); // name will be undefined
Confusion can really begin to set in when using the same variable name inside and outside of a function.
var name = "Jonathan";
function showme()
{
var name = "Snook";
alert(name); // will display "Snook"
}
showme();
alert(name); // will display "Jonathan"
Some languages have syntax to prevent these types of errors from occurring. In PHP, for example, to use a global variable inside a function, you must use the global keyword.