Sunday, September 7, 2014

JavaScript Scopes to Functions Not Files

"The cloud-capped towers, the gorgeous palaces,
The solemn temples, the great globe itself,
Yea, all which it inherit, shall dissolve,
And, like this insubstantial pageant faded,
"Shakespeare, The Tempest
Act IV, Scene I, Lines 152-155

While taking this Pluralsight class by Joe Eames I saw a short demo of how in JavaScript variables are scoped to functions and not to files.  I kind-of-all-ready knew this but have not really looked into it.

Here is a quick demo to show what it means to the browser.

See this Plunker if you want to play around with the code.

The browser loads the index.html file which cause it to load and execute a.js, b.js, and c.js.

  • index.html
    • a.js
    • b.js
    • c.js
The browser executes the JavaScript in the following order.
  1. a.js executes adding the variable a to the global name space (which in the browser is window)
  2. b.js executes calling console.log with the variable a
  3. c.js executes adding the function f to the global name space
  4. c.js then executes the function f (this is called an iffe
    1. which adds the variable x to function f's scope
    2. then calls console.log with the variable x
  5. c.js then tries to call console.log with a variable x but there is not an x in the global name space
With the scope looking like the following.
  • window
    • variable a
      • "this is from a.js"
    • function f
      • variable x
        • "scoped to function f"
Looking at the scope it is easy to see why the call to console.log with a in the file b.js works but the call to console.log with x in the c.js outside of the function f fails.

This is nothing new, but with JavaScript taking off in popularity this is something to keep in mind since it is very different than how most programming languages work.