Java Reference
In-Depth Information
Scope is an important concept in programming. It refers to where a variable is visible and
In JavaScript, a function creates its own local scope . This means that any local variables
defined inside a function using the var keyword are not accessible outside the function.
Global Scope
Any variable declared outside of any function is said to have global scope . That means that
it is accessible everywhere in the program. While this may seem to be a good idea at first,
it is not considered good practice. A ninja will try to limit the number of global variables
to a minimum, because any variable that shares the same name will clash and potentially
overwrite each other's values. It might seem unlikely that this would happen, but it is all too
common in large programs when you forget which variables you have used―think how of-
ten we have used the variable i in for loops already! It can also be a problem when you are
writing code in teams or if you're using code libraries that may use the same variable names
as some of your code.
Local Scope
Any variable that is declared inside a function using the var statement will only be available
inside that function. This is known as having local scope , as the variable is only visible in
the locality of the function (in other words, inside the function block).
If the var statement is not used, the variable will have global scope and be available outside
the function. This can be demonstrated in the following example, where the variable a can
have two different values depending on whether it is defined inside or outside a function:
var a = 1;
function locala() {
var a = 3; // local variable
console.log("a inside function: " + a);
Search WWH ::

Custom Search