What is the scope of a variable?
Mar 18, 2009 | English | By Hazel | No Comments | Leer en EspaolWhen we talk about “scope”, we are referring to the scope or the area where a variable can be used, in this chapter we will see how JavaScript handles this concept.
In JavaScript the scope of the variables takes place in a function and not in blocks of code (if, while, switch, etc.) like in languages Java or C/C++; in other words if a variable gets defined inside of a conditional block (if) this variable can be used in all the function and not only in the conditional block. Let’s see the next example:
if(true){
var test = 'is it a block var?';
}
function testing(){
var test = 'testing scope!';
}
testing();
console.debug(test);
Inside of the condition the variable “test” was defined, in languages like Java this variable would exists only inside of the condition, but in JavaScript the scope is different because the variable “test” was defined in the “global scope” and not inside of the conditional block. Furthermore the other variable that was defined inside of the “testing” function only exists within that function.
It is important to remember that the variables that are declared in the “global scope” are properties of the object “window”, to verify this assertion let’s do the following:
var global = 'this is a global var!'; console.debug(window.global);
Another thing to consider is that when the variables are not declared using the keyword “var” it doesn’t matter if they are inside of a function or not, these variables are automatically defined in the “global scope”.
function globalScopeFunction(){
globalScope = 'this is a new var in the global scope!';
}
globalScopeFunction();
console.debug(globalScope);
console.debug(window.globalScope);
It is important to know these concepts because we will use them later on, so now we know what is exactly the scope of the variables and where we can use it.






