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:

a code file with arrows drawn to show outer and inner scope in the code file

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.

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.