The scope of a variable is where the variable "exists" in your code. When you create a variable, you'll need to know where you can use it.
Let's see a diagram of inner and outer scope:
In the above diagram, what will the name variable be if we call SetName()? We'll find out below.
With variables, there are two very important things to remember:
If I declare a variable in JavaScript:
var name = "Ted";
and omit the var keyword:
name = "Ted";
then the variable is global, even if the variable is set inside a function:
var name = "Dave"
function SetName() {
name = "Ted";
}
SetName();
alert(name);
(this alerts Ted)
If I declare a variable in an outer scope, it is visible in the inner scope:
var name = "Ted";
function ShowName() {
alert(name);
}
ShowName();
(this alerts Ted)
The inner function ShowName() below:
function SetName() {
var name = "Ted";
var ShowName = function() {
alert(name);
}
ShowName();
}
SetName();
can see name in the outer scope, and alerts Ted.
If the inner scope duplicates a name from the outer scope:
function SetName() {
var name = "Ted";
var ShowName = function(name) {
alert(name);
}
ShowName("Jim");
}
SetName();
then the outer variable gets shadowed (not used). The above alerts Jim.
Leave a comment