Your browser does not support JavaScript!
Upvotes Anonymous 0 User 0

Variable Scope in JavaScript

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:

1. Always use var to declare (create) variables.
2. Variables created in an outer scope exist in the inner scope (unless you declare a variable in the inner scope with the same name).
Global variables
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)
Inner Scope Sees Outer
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.
Variable Shadowing
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.
Was this helpful?

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License